2015-06-03 166 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