[英]Ruby: Swap out hash key with matching value from other hash
I have these hashes: 我有这些哈希:
hash = {1 => "popcorn", 2 => "soda"}
other_hash = {1 => "dave", 2 => "linda", 3 => "bobby_third_wheel"}
I would like to replace the id reference with the name associated to the id in the second hash, if there is a record in other_hash
that has nothing to match, it should just be dropped in the resulting hash. 我想将id引用替换为与第二个哈希中的id关联的名称,如果
other_hash
中有一条没有任何内容匹配的记录,则应该将其删除到生成的哈希中。 Like this: 像这样:
the_one_hash_to_rule_them_all = {"dave" => "popcorn", "linda" => "soda"}
You can easly use this each_with_object
method on "primary" hash with names. 您可以在名称上的“主”哈希中
each_with_object
使用此each_with_object
方法。
other_hash.each_with_object({}) { |(id, name), h| h[name] = hash[id] if hash.key?(id) }
# => {"dave"=>"popcorn", "linda"=>"soda"}
hash.each_with_object({}){|(k,v), res| res[other_hash[k]] = v}
# => {"dave"=>"popcorn", "linda"=>"soda"}
First, an "array-comprehension" with the pattern enumerable.map { expr if condition }.compact
and finally an Array#to_h
. 首先,使用模式
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"}
Also: 也:
h = other_hash.select { |k, v| hash.has_key?(k) }.map { |k, v| [v, hash[k]] }.to_h
hash.map{|k, v| [other_hash[k], v]}.to_h
# => {"dave"=>"popcorn", "linda"=>"soda"}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.