awongCM
awongCM

Reputation: 927

Convert multi-dimensional array format in Ruby/Rails

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

Answers (4)

user456814
user456814

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

xdazz
xdazz

Reputation: 160833

You could create the hash directly:

Group.all.inject({}) { |h, g| h[g.name] = g.id; h }

Upvotes: 2

sawa
sawa

Reputation: 168081

[["Bankruptcy Group", 1], ["PIA Group", 2], ["Liquidation Group", 3]].to_h

Upvotes: 3

Koraktor
Koraktor

Reputation: 42893

array = Group.all.collect { |group| [ group.name, group.id ] }
hash = Hash[array]

Upvotes: 0

Related Questions