I\'m trying to get a common element from a group of arrays in Ruby. Normally, you can use the & operator to compare two arrays, which returns elements
Can't you just do a comparison of the first two, take the result and compare it to the next one etc? That seems to meet your criteria.
Behold the power of inject
! ;)
[[1,2,3],[1,3,5],[1,5,6]].inject(&:&)
=> [1]
As Jordan mentioned, if your version of Ruby lacks support for &-notation, just use
inject{|acc,elem| acc & elem}
Why not do this:
def get_common_elements_for_hash_of_arrays(hash)
ret = nil
hash.each do |key, array|
if ret.nil? then
ret = array
else
ret = array & ret
end
end
ret = Array.new if ret.nil? # give back empty array if passed empty hash
return ret
end