我有这些散列:
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"}
最佳答案
您可以轻松地在带有名称的“主要”哈希上使用此each_with_object
方法。
other_hash.each_with_object({}) { |(id, name), h| h[name] = hash[id] if hash.key?(id) }
# => {"dave"=>"popcorn", "linda"=>"soda"}
关于Ruby:用其他散列中的匹配值交换散列键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35599830/