2012-05-24 46 views
1

我想比較兩個哈希以確定哪些值可以匹配。例如:如何比較兩個哈希中的元素

hash1 = { 
    "hash1_key_a" => 1, 
    "hash1_key_b" => 2 
} 

hash2 = { 
    "hash2_key_a" => 1, 
    "hash2_key_b" => 3, 
    "hash2_key_c" => 4 
} 

# The method here should display the matching keys & values, 
# and then delete them from their hashes. For example: 

puts "#{hash1_key_a};#{hash2_key_a};1" # 1 is representing the referral we should 
             # put in for the value 

任何人都可以引導我在正確的方向嗎?

+0

你可以做一個天真的雙循環。 –

+0

你只是這樣做。使用'each_with_index'和比較運算符'=='。對你來說沒有什麼神奇的方法。 – meagar

+0

@meagar:但可能有一個。 Ruby每一天都讓我感到驚喜:) –

回答

0

散列有不同的鍵嗎?然後你可以這樣做:

hash1.merge(hash2).group_by{|k,v| v}.each{ |v,ks| 
    puts "#{ ks.map(&:first)*';' };#{ v }" 
} 
+0

J -_- L,那只是天才。謝謝。 – ChristofferJoergensen