简体   繁体   中英

change hash key through function call

I have a hash where the keys are country_id's and I would like to change the country_id keys to actually have the name of the country. I have a function that can do the id to name conversion but I can't figure out how to get the keys updated and mapped correctly to their current values.

Also I'm not able to use transform_keys due to the version of ruby\\rails I'm on.

I don't know what country will be selected so I need a way of looping through the keys and updating them, then storing back to the hash or a new hash with the values mapped correctly.

the hash I have is called @trending_countries the keys are currently the country_id that needs to be updated and the value consists of a count for that particular country.

@trending_countries = {22=>2, 34=>3} and I would like it in the format of @trending_countries = {United States=>2, Canada=>3}

I tried doing the below in my controller

@trending_countries.each {|k, v| @trending_countries[k] = Country.get_country_name(k)}

the function doing the id to name conversion is in a separate model called 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

一种实现方法如下:

old_hash.map { |key, value| [Country.get_country_name(key), value] }.to_h
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}

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