Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hash#slice like method that returns nil if given key are not present

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.

like image 981
ironsand Avatar asked Jul 29 '15 20:07

ironsand


1 Answers

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 }
like image 67
Rob Di Marco Avatar answered Oct 25 '22 16:10

Rob Di Marco