Pierre Olivier Tran Pierre Olivier Tran - 1 year ago 84
Ruby Question

intersection of a ruby array and the keys of a hash

Is it possible to get the intersection of an array and just the keys of a hash?

I know that the

operator returns the intersection of two arrays, but I'd like to use the values instead of the
value + key

Let's say, I have an array and a hash :

a1 = [ 'test1', 'test2', 'test3' ]
a2 = { 'test3' => 'value3', 'test4'=>'value4', 'test5'=>'value5' }

is there a way to return
from these?

Answer Source


arr = ['value1', 'value2', 'value3']
hsh = {:key1 => 'value3', :key2=>'value4', :key3=>'value5'}

you can convert hsh to an array of values with the .values method and use the & operator to compare the hash values with an array.

arr & hsh.values

=> ["value3"]