I'm using Hash#slice
method in my rails environment.
slice
method works like this:
{ a: 1, b: 2, d: 4 }.slice(:a, :c, :d)
=> {:a=>1, :d=>4}
But I want to return a nil
if given key are not present, like this:
{ a: 1, b: 2, d: 4 }.slice(:a, :c, :d)
=> {:a=>1, :c=>nil, :d=>4}
This is what I wrote for the function, is there better way to write this function?
hash = {a: 1, b: 2, d: 4}
keys = [:a, :c, :d]
keys_not_present = keys.map { |key| key unless hash.has_key?(key) }.compact
keys_not_present = keys_not_present.zip([nil]*keys_not_present.size).to_h
hash.slice(*keys).merge(keys_not_present)
The order of the hash is not concerned.
I would use a reduce
of the terms you are interested in:
hash = {a: 1, b: 2, d: 4}
[:a, :c, :d].reduce({}) {|h, k| h[k] = hash[k]; h }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With