Use hash select for array

I have a hash

h = {a=> 1, b=> 2, c=> 3}

and array

a = [a, b]

Can i use

h.select {|k,v| k == array_here?}

To select all elements from an array existing in a hash?

I found a solution

h.select {|k,v| a.include?(k) }
+5
source share
4 answers

One possible and easiest answer:

h.select {|k,v| a.include?(k) }
0
source

You go about it back. Try the following:

a.select {|e| h.has_key? e }
+2
source

You could achieve this with something like:

a.each do |arr_elem| 
  new_hash[arr_elem] = h[arr_elem] unless h[arr_elem].nil?
end
+1
source

If you really want what you would ask (for example, array elements that are present as keys in the hash):

h = {:a => 1, :b => 2, :c => 3}
a = [:a, :b, :d]
a & h.keys
+1
source

All Articles