Is this the best way to grab common elements from a Hash of arrays?

后端 未结 3 1728
[愿得一人]
[愿得一人] 2021-01-03 08:52

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

相关标签:
3条回答
  • 2021-01-03 09:36

    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.

    0 讨论(0)
  • 2021-01-03 09:39

    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}
    
    0 讨论(0)
  • 2021-01-03 09:51

    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
    
    0 讨论(0)
提交回复
热议问题