仅具有重复键的哈希值

时间:2016-03-02 20:05:32

标签: ruby

hashes = [{:auchan=>2.3, :biedronka=>2.6, :lidl=>2.4},
          {:auchan=>2.5, :biedronka=>3, :lidl=>2.4, :zabka=>3.5},
          {:auchan=>1.5, :lidl=>1.1, :zabka=>2},
          {:auchan=>1.1, :lidl=>0.8, :zabka=>1.5, :biedronka=>1.6}]

我想只用重复键来获取哈希值。

我尝试了这个,但它只适用于2个哈希,而不是更多:

hashes[0].merge hashes[1].select { |k| hashes[0].keys.include? k }

hashes.same_keys => [{:auchan=>2.3, :biedronka=>2.6, :lidl=>2.4}, 
                     {:auchan=>2.5, :biedronka=>3, :lidl=>2.4 }, 
                     {:auchan=>1.1, :lidl=>0.8, :biedronka=>1.6}]

2 个答案:

答案 0 :(得分:1)

您可以先找到密钥,然后映射您的哈希:

same_keys = hashes.map(&:keys).reduce(&:&)

hashes.map { |h| h.slice(*same_keys) }
=>[{:auchan=>2.3, :lidl=>2.4},
   {:auchan=>2.5, :lidl=>2.4},
   {:auchan=>1.5, :lidl=>1.1},
   {:auchan=>1.1, :lidl=>0.8}]

答案 1 :(得分:0)

我不太确定你想要什么,但是假设你想要一个数组,其中每个输入哈希映射到一个哈希,该哈希只包含输入中每个哈希中存在的键,下面是应该工作:

我已经在Ruby 1.9.3中对此进行了测试,但它也适用于更新版本:

#!/usr/bin/env ruby

require 'set'

hashes = [
  {:auchan=>2.3, :biedronka=>2.6, :lidl=>2.4},
  {:auchan=>2.5, :biedronka=>3, :lidl=>2.4, :zabka=>3.5},
  {:auchan=>1.5, :lidl=>1.1, :zabka=>2},
  {:auchan=>1.1, :lidl=>0.8, :zabka=>1.5, :biedronka=>1.6}
]

keys = nil
hashes.each do |h|
  if keys.nil?
    keys = Set.new(h.keys)
  else
    keys = keys & h.keys
  end
end
puts keys.to_a

result = hashes.map do |h|
  h.select{|k,v| keys.include?(k)}
end

puts result

此外,如果您尝试保存字节,则可以使用此oneliner设置keys

keys = hashes.map(&:keys).reduce{|t, h| t & h}