Reputation: 18871
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
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