2016-03-02 67 views
0
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}] 
+1

你要求的'數組'方法'same_keys'?另外,請解釋(通過編輯)「重複鍵」的含義,併爲您的示例顯示期望的結果,解釋爲什麼包含一些哈希,而其他哈希不包含。 –

回答

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 

此外,如果你試圖保存字節,可以設置keys這個oneliner代替:

keys = hashes.map(&:keys).reduce{|t, h| t & h} 
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}]