如何匹配两个不同哈希值中的哈希值

时间:2015-06-03 05:53:20

标签: ruby hash

我试图在两个独立的哈希中计算匹配的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

3 个答案:

答案 0 :(得分:0)

这将返回两个散列中常见的值

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

答案 1 :(得分: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]

答案 2 :(得分:0)

好像你似乎只想找到一个共同的appid。如果这就是你要做的全部,那么可能比循环哈希更有效。

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