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

后端 未结 3 1729
[愿得一人]
[愿得一人] 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: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
    

提交回复
热议问题