Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use hash select for an array

Tags:

ruby

I have a hash

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

and an array

a = [a, b]

Is it possible to use

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

To select all elements from the array that exists in the hash?

I Found the Solution

h.select {|k,v| a.include?(k) }
like image 789
glarkou Avatar asked Oct 10 '22 14:10

glarkou


2 Answers

You're going about it backwards. Try this:

a.select {|e| h.has_key? e }
like image 118
jtbandes Avatar answered Oct 13 '22 04:10

jtbandes


You could achieve that with something like:

a.each do |arr_elem| 
  new_hash[arr_elem] = h[arr_elem] unless h[arr_elem].nil?
end
like image 20
Tudor Constantin Avatar answered Oct 13 '22 05:10

Tudor Constantin