我想在两个单独的哈希中计算匹配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'。不知何故,我不认为这是你的想法。 –