我想在兩個單獨的哈希中計算匹配appid的數量,但我的解決方案感覺笨重。有人可以提出一個「紅寶石」的方式來做到這一點?如何在兩個不同的哈希中匹配哈希值
#hash from an array: {"appid"=>240, "playtime_forever"=>103} {"appid"=>2670, "playtime_forever"=>1099}
#This is Steam data for those interested
def games_in_common(friend_hash,other_hash)
arr1=Array.new
arr2=Array.new
other_hash.keys.each{|k|
arr1<<other_hash[k]
}
friend_hash.keys.each{|k|
arr2<<friend_hash[k]
}
return arr1 & arr2
end
嘗試使用[GROUP_BY(http://ruby-doc.org/core-2.2.2/Enumerable.html#method-i-group_by) –
爲什麼不'ARR2 = friend_hash.values'和'arr1 = other_hash.values',而不是通過循環單獨插入它 – Abhi
看起來''appid''是一個關鍵。如果是這樣,兩個哈希(例如'h1'和'h2')中的每一個最多隻有一個這樣的鍵,這意味着您的答案是零或一:'(h1.key(「appid」)&& h2.key 「appid」)&& h1 [「appid」] == h2 [「appid」])? 1:0'。不知何故,我不認爲這是你的想法。 –