如何从指定键出现2次以上的哈希数组中选择哈希值

时间:2015-12-02 07:58:18

标签: ruby hash

我想在companies出现次数超过2次时选择code

companies = [{code: 10, value: 3}, {code: 3, value: 5}, {code: 10, value: 4}, {code: 5, value: 10}]

companies.select{|c| companies.select{|c_inside| c_inside[:code] == c[:code]}.count > 1 }
=> [{:code=>10, :value=>3}, {:code=>10, :value=>4}]

此代码有效,但似乎有点多余。是否有更好的方法来编写这样的函数?

3 个答案:

答案 0 :(得分:2)

这是另一种选择:

companies.group_by{ |hsh| hsh[:code] }
  .values
  .select{ |val| val.count > 1 }
  .flatten

#=> [{:code=>10, :value=>3}, {:code=>10, :value=>4}]

答案 1 :(得分:1)

另一种方式。

companies.group_by { |e| e[:code] }
         .select { |_, v| v.size > 1 }
         .flat_map { |_, v| v }
#=> [{:code=>10, :value=>3}, {:code=>10, :value=>4}]

答案 2 :(得分:1)

此代码使用n次迭代而不是n ^ 2次迭代:

companies = [{code: 10, value: 3}, {code: 3, value: 5}, {code: 10, value: 4}, {code: 5, value: 10}]
final_value = []
companies.each.with_object({}) do |c, hash|
  hash[c[:code]] = [] if hash[c[:code]] == nil
  hash[c[:code]] << c
  if hash[c[:code]].count == 2
    final_value += hash[c[:code]]
  elsif hash[c[:code]].count > 2
    final_value << c
  end
end

puts final_value