ruby - Most succinct method that takes a single-level hash argument and returns a copy with nil values -
help me write succinct method takes 1 argument (a single-level hash) , returns copy values set nil.
example input hash
{ email: 'hans@moleman.com', first_name: 'hans', last_name: 'moleman' }
returned value
{ email: nil, first_name: nil, last_name: nil }
what this?
new_hash = hash[original_hash.keys.zip([])]
take keys of hash, zip empty array pairs of keys nil, , use hash[]
convert hash.
or, @mu_is_too_short pointed out in comments, way might less tricky read is:
new_hash = hash[original_hash.keys.map { |k| [k, nil] }]
this alternative, credit @mu.
Comments
Post a Comment