Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 733
Lee Avatar asked Apr 01 '11 22:04

Lee


People also ask

Is it possible to convert an active record to a hash?

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.

How to convert ActiveRecord objects to Ruby hashes?

You should use as_json method which converts ActiveRecord objects to Ruby Hashes despite its name

What is a hash return?

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.

How to convert ActiveRecord data to hash in rails?

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.


1 Answers

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 } 
like image 89
Phrogz Avatar answered Oct 04 '22 16:10

Phrogz