Build hash from collection of ActiveRecord Models
I'm trying to build a hash from a Model.
This is the type of hash I want to build.
{"United Sates" => "us", "United Kingdom" => "uk" .....}
I have tried so many ways now I'm just going around in circles.
Here 开发者_开发技巧are just some of my poor attempts.
select = Array.new
countries.each do |country|
# select.push({country.name => country.code })
# select[country.name][country.code]
end
h = {}
countries.each do |c|
# h[] = {c.name => c.code}
# h[] ||= {}
# h[][:name] = c.name
# h[][:code] = c.code
#h[r.grouping_id][:name] = r.name
# h[r.grouping_id][:description] = r.description
end
Please can some advise.
Thank You
Here are some one-liner alternatives:
# Ruby 2.1+
name_to_code = countries.map{ |c| [c.name,c.code] }.to_h
# Ruby 1.8.7+
name_to_code = Hash[ countries.map{ |c| [c.name,c.code] } ]
# Ruby 1.8.6+
name_to_code = Hash[ *countries.map{ |c| [c.name,c.code] }.flatten ]
# Ruby 1.9+
name_to_code = {}.tap{ |h| countries.each{ |c| h[c.name] = c.code } }
# Ruby 1.9+
name_to_code = countries.to_a.each_with_object({}){ |c,h| h[c.name] = c.code }
Courtesy of @Addicted's comment below:
# Ruby 1.8+
name_to_code = countries.inject({}){ |r,c| r.merge c.name=>c.code }
With Rails 4 you could simply do:
country_codes = Hash[Country.pluck(:name, :code)]
Which I think is optimal because you don't have to load a bunch of country objects and iterate through them
The pluck method on Rails 3 does not allow more than one attribute, but you could do something like:
country_codes = Hash[Country.connection.select_rows(Country.select('name, code').to_sql)]
My favorite Answer these days is to use pluck
and to_h
countries.pluck(:name, :code).to_h
# => {"United Sates" => "us", "United Kingdom" => "uk" .....}
to reverse them and have the code first
countries.pluck(:code, :name).to_h
# => {"us" => "United Sates", "uk" => "United Kingdom" .....}
Define the countries hash then fill it from your records.
countries_hash = {}
countries.each do |c|
countries_hash[c.name] = c.code
end
精彩评论