Reputation: 927
I have the following code below.
Group.all.collect {|group| [ group.name, group.id ]}.inspect
And this one outputs below.
[["Bankruptcy Group", 1], ["PIA Group", 2], ["Liquidation Group", 3]]
I want to convert to a different format like below.
{"Bankruptcy Group" => 1, "PIA Group"=> 2, "Liquidation Group"=> 3}
How do I do this?
Upvotes: 0
Views: 441
Reputation:
The to_h
method of Enumerable
can be used to convert enumerable objects to hashes when each item in the object can be interpreted as an array of the form [key, value]
:
Group.all.map { |g| [g.name, g.id] }.to_h
From the documentation for to_h
:
Returns the result of interpreting
enum
as a list of[key, value]
pairs.
Upvotes: 0
Reputation: 160833
You could create the hash directly:
Group.all.inject({}) { |h, g| h[g.name] = g.id; h }
Upvotes: 2
Reputation: 168081
[["Bankruptcy Group", 1], ["PIA Group", 2], ["Liquidation Group", 3]].to_h
Upvotes: 3
Reputation: 42893
array = Group.all.collect { |group| [ group.name, group.id ] }
hash = Hash[array]
Upvotes: 0