我有一个哈希,其中的密钥是country_id,我想更改country_id密钥以实际具有国家/地区的名称。我有一个可以执行id到名称转换的函数,但是我不知道如何更新密钥并将其正确映射到它们的当前值。
由于我使用的ruby \ rails版本,我也无法使用transform_keys
。
我不知道将选择哪个国家,所以我需要一种方法来遍历键并更新它们,然后将其存储回散列或具有正确映射值的新散列。
我拥有的哈希称为@trending_countries
,密钥当前是需要更新的country_id,并且值包含该特定国家/地区的计数。
@trending_countries = {22=>2, 34=>3}
,我希望以@trending_countries = {United States=>2, Canada=>3}
我尝试在控制器中执行以下操作
@trending_countries.each {|k, v| @trending_countries[k] = Country.get_country_name(k)}
执行id到名称转换的函数在一个名为Country的单独模型中。
# returns the country name when a country id is given.
def self.get_country_name(country_id)
country = self.find_by(id: country_id)
return country.name
end
答案 0 :(得分:2)
做到这一点的一种方法是:
old_hash.map { |key, value| [Country.get_country_name(key), value] }.to_h
答案 1 :(得分:0)
old_hash = { 62=>:wee, 12=>:big, 8=>:medium }
country_id_to_name = { 62=>"Monaco", 8=>"France", 12=>"China" }
old_hash.each_with_object({}) { |(k,v),h| h[country_id_to_name[k]] = v }
#=> {"Monaco"=>:wee, "China"=>:big, "France"=>:medium}