简体   繁体   中英

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. 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.

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 .

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"}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM