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, ...>,
#<Articl开发者_StackOverflow社区e 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?
>> articles.inject({}) { |k,v| k[v.id] = v.category_id; k }
Hash[articles.map {|a| [a.id, a.category_id]}]
In Ruby 1.9, you can use each_with_object
articles.each_with_object({}) { |hash, article| hash[article.id] = article.category_id }
精彩评论