Is this the best way to capture common elements from an array of arrays?

I am trying to get a common element from an array group in Ruby. You can usually use & to compare two arrays that return elements that are present or common in both arrays. This is all good, except when you are trying to get common elements from more than two arrays. However, I want to get common elements from an unknown, dynamic number of arrays that are stored in a hash.

I had to resort to using the eval () method in ruby, which executes the string as actual code. Here is the function I wrote:

  def get_common_elements_for_hash_of_arrays(hash) # get an array of common elements contained in a hash of arrays, for every array in the hash.
       # ["1","2","3"] & ["2","4","5"] & ["2","5","6"] # => ["2"]
       # eval("[\"1\",\"2\",\"3\"] & [\"2\",\"4\",\"5\"] & [\"2\",\"5\",\"6\"]") # => ["2"]
       eval_string_array = Array.new # an array to store strings of Arrays, ie: "[\"2\",\"5\",\"6\"]", which we will join with & to get all common elements
       hash.each do |key, array|
          eval_string_array << array.inspect 
       end
       eval_string = eval_string_array.join(" & ") # create eval string delimited with a & so we can get common values 
       return eval(eval_string)
  end

example_hash = {:item_0 => ["1","2","3"], :item_1 => ["2","4","5"], :item_2 => ["2","5","6"] }
puts  get_common_elements_for_hash_of_arrays(example_hash) # => 2

, ... eval, ? ? - (, , ). - - , .

, , , .

+3
3

inject!;)

[[1,2,3],[1,3,5],[1,5,6]].inject(&:&)
=> [1]

, Ruby -notation,

inject{|acc,elem| acc & elem}
+15

, ..? .

0

Why not do it:

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
source

Source: https://habr.com/ru/post/1738538/


All Articles