我试图从Ruby中的一组数组中获取一个公共元素.通常,您可以使用 &运算符来比较两个数组,这两个数组返回两个数组中存在或共同的元素.这一切都很好,除非您尝试从两个以上的数组中获取常用元素.但是,我希望从未知的动态数量的数组中获取常见元素,这些数组存储在散列中.
我不得不求助于在ruby中使用eval()方法,它将字符串作为实际代码执行.这是我写的函数:
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
Run Code Online (Sandbox Code Playgroud)
这很有效,但我想知道...... 真的,真的吗? 这是最好的方法吗?是否有任何其他方法来实现这一点(当然,除了递归功能).如果有人有任何建议,我会全力以赴.
否则,如果您需要从组或数组散列中获取公共项或元素,请随意使用此代码,此代码也可以轻松地适用于搜索数组数组.
Mla*_*vić 16
看吧!的力量inject!;)
[[1,2,3],[1,3,5],[1,5,6]].inject(&:&)
=> [1]
Run Code Online (Sandbox Code Playgroud)
正如Jordan所提到的,如果您的Ruby版本缺乏对&-notation的支持,请使用
inject{|acc,elem| acc & elem}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1740 次 |
| 最近记录: |