2015-06-03 66 views
0

我想在两个单独的哈希中计算匹配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 
+0

尝试使用[GROUP_BY(http://ruby-doc.org/core-2.2.2/Enumerable.html#method-i-group_by) –

+0

为什么不'ARR2 = friend_hash.values'和'arr1 = other_hash.values',而不是通过循环单独插入它 – Abhi

+0

看起来''appid''是一个关键。如果是这样,两个哈希(例如'h1'和'h2')中的每一个最多只有一个这样的键,这意味着您的答案是零或一:'(h1.key(“appid”)&& h2.key “appid”)&& h1 [“appid”] == h2 [“appid”])? 1:0'。不知何故,我不认为这是你的想法。 –

回答

0

如果我理解正确的,你这回是共同的价值观在这两个哈希

def games_in_common(friend_hash,other_hash) 
    other_hash.values & friend_hash.values 
end 
0

,在这里你去:

▶ h1 = [{"appid"=>240, "playtime_forever"=>103}, 
▷  {"appid"=>2670, "playtime_forever"=>1099}] 
▶ h2 = [{"appid"=>240, "playtime_forever"=>103}, 
▷  {"appid"=>2671, "playtime_forever"=>1099}] 
▶ h1.map { |e| e['appid'] } & h2.map { |e| e['appid'] } 
#⇒ [240] 
0

好像你只是试图查找是否有共同的appid。如果这就是你想要做的这一切,可能比循环遍历哈希更有效。

def games_in_common(friend_hash, my_hash) 
    friend_hash['appid'] == my_hash['appid'] ? friend_hash['appid'] : nil 
end