Hash#slice like method that returns nil if given key are not present
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 }
Here's my solution; it creates a new Hash from the keys
array with nil
values, and merges that with the results of the slice:
> Hash[keys.zip].merge(hash.slice(*keys))
=> {:a=>1, :c=>nil, :d=>4}