Lee Lee - 7 months ago 33
Ruby Question

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

Answer

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