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
You can also convert any ActiveRecord objects to a Hash with serializable_hash and you can convert any ActiveRecord results to an Array with to_a, so for your example : +1 For suggesting serializable_hash - this is the first time I've ever come across an answer that mentions this.
You should use as_json method which converts ActiveRecord objects to Ruby Hashes despite its name
What's this? Returns a new object of the collection type that has been instantiated with attributes and linked to this object, but have not yet been saved. You can pass an array of attributes hashes, this will return an array with the new objects.
You can also convert any ActiveRecord objects to a Hash with serializable_hash and you can convert any ActiveRecord results to an Array with to_a, so for your example : And if you want an ugly solution for Rails prior to v2.3 Show activity on this post. May be? Show activity on this post.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With