这是从数组散列中获取公共元素的最佳方法吗? [英] Is this the best way to grab common elements from a Hash of arrays?

查看:42
本文介绍了这是从数组散列中获取公共元素的最佳方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 Ruby 中的一组数组中获取一个公共元素.通常,您可以使用& 运算符用于比较两个数组,它返回两个数组中存在或共有的元素.这一切都很好,除非您试图从 两个 以上的数组中获取公共元素.但是,我想从存储在散列中的未知的动态数组中获取公共元素.

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 that are present or common in both arrays. This is all good, except when you're trying to get common elements from more than two arrays. However, I want to get common elements from an unknown, dynamic number of arrays, which are stored in a hash.

我不得不求助于在 ruby​​ 中使用 eval() 方法,它将字符串作为实际代码执行.这是我写的函数:

I had to resort to using the eval() method in ruby, which executes a string as actual code. Here's 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,真的吗?这是最好的方法吗?是否还有任何其他方法来实现这一点(当然,除了递归函数).如果有人有任何建议,我会全神贯注.

This works and is great, but I'm wondering...eval, really? Is this the best way to do it? Are there even any other ways to accomplish this(besides a recursive function, of course). If anyone has any suggestions, I'm all ears.

否则,如果您需要从数组或数组散列中获取公共项或元素,请随意使用此代码,此代码也可以很容易地用于搜索数组数组.

Otherwise, Feel free to use this code if you need to grab a common item or element from a group or hash of arrays, this code can also easily be adapted to search an array of arrays.

推荐答案

看看 inject 的威力吧!;)

Behold the power of inject! ;)

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

正如 Jordan 提到的,如果您的 Ruby 版本不支持 &-notation,请使用

As Jordan mentioned, if your version of Ruby lacks support for &-notation, just use

inject{|acc,elem| acc & elem}

这篇关于这是从数组散列中获取公共元素的最佳方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆