Reputation: 48500
I have an array of Active Record objects. I'd like to create a hash that serves as an index. My Active Record objects have the properties name
and value
.
Ideally I'd like to iterate over the array and create a hash that will create something similar to:
hash[name] = value
What's the best way to create an array foo
to create a hash similar to the one above?
Upvotes: 4
Views: 55
Reputation: 12427
You can use the method Hash::[]
.
relation = Record.where("query")
Hash[
relation.to_a.map do |obj|
[obj.name, obj.value]
end
]
Upvotes: 0
Reputation: 29092
Something like this would work:
hash = {}
Model.all.map { |i| hash[i.id] = i }
hash
should then evaluate to:
{
:1 => #<ActiveRecord:1>,
:2 => #<ActiveRecord:2>,
...
}
Upvotes: 2