我有这些杂碎:

hash  = {1 => "popcorn", 2 => "soda"}
other_hash = {1 => "dave", 2 => "linda", 3 => "bobby_third_wheel"}

我想用与第二个散列中的id相关联的名称替换id引用,如果other_hash中有一个记录没有任何匹配项,则应该将其丢弃在结果散列中。这样地:
the_one_hash_to_rule_them_all = {"dave" => "popcorn", "linda" => "soda"}

最佳答案

首先是模式enumerable.map { expr if condition }.compact的“数组理解”,最后是Array#to_h

h = other_hash.map { |k, v| [v, hash[k]] if hash.has_key?(k) }.compact.to_h
#=> {"dave"=>"popcorn", "linda"=>"soda"}

也:
h = other_hash.select { |k, v| hash.has_key?(k) }.map { |k, v| [v, hash[k]] }.to_h

10-08 04:26