Backo
Backo

Reputation: 18871

How to build an hash from an array of class object in one statement

I am using Ruby on Rails 3.0.7 and I would like to perform the following in one statement.

I have an array of class objects:

# >> articles.inspect
[
  #<Article id: 1,  category_id: 2, ...>,
  #<Article id: 10, category_id: 5, ...>,
  #<Article id: 6,  category_id: 9, ...>,
  #<Article id: 9,  category_id: 3, ...>,
  #<Article ...>
]

I would like (by using one statement; that is, "only one code line") to build an hash like this:

{
  "1"   => 2,
  "10"  => 5,
  "6"   => 9,
  "9"   => 3,
  "..." => ...,
}

where hash keys are article.id values and hash values are article.category_id values.

How can I do that?

Upvotes: 1

Views: 151

Answers (3)

rubyprince
rubyprince

Reputation: 17793

In Ruby 1.9, you can use each_with_object

articles.each_with_object({}) { |hash, article| hash[article.id] = article.category_id }

Upvotes: 1

Yossi
Yossi

Reputation: 12100

Hash[articles.map {|a| [a.id, a.category_id]}]

Upvotes: 3

Joshua Smith
Joshua Smith

Reputation: 6621

 >> articles.inject({}) { |k,v| k[v.id] = v.category_id; k }

Upvotes: 5

Related Questions