[英]Ruby: Swap out hash key with matching value from other hash
我有這些哈希:
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
使用此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"}
首先,使用模式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
hash.map{|k, v| [other_hash[k], v]}.to_h
# => {"dave"=>"popcorn", "linda"=>"soda"}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.