0

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?

2
  • Are you using Ruby on Rails? There might be ActiveRecord methods that can be used to return model ids and names directly from the database using SQL. Commented Mar 20, 2014 at 7:05
  • Yes I do. Hence for the original code at the beginning of the sentence. I am still RoR newbie so I don't know a lot of ActiveRecord's API that I can fully muster it... Commented Mar 20, 2014 at 12:25

4 Answers 4

3
[["Bankruptcy Group", 1], ["PIA Group", 2], ["Liquidation Group", 3]].to_h
Sign up to request clarification or add additional context in comments.

1 Comment

I like this one.. simple and in one go.. +1
2

You could create the hash directly:

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

1 Comment

Thanks xdazz. I like this one better. Save me lines of code to write them out. Thanks Heaps!
0
array = Group.all.collect { |group| [ group.name, group.id ] }
hash = Hash[array]

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.