jlstr
jlstr

Reputation: 3056

How to convert an array into a Dictionary in Ruby?

I've been trying unsuccessfully to solve a problem I was asked during an interview, it was exactly like this:

Consider the following structure in Ruby:

['dog', 'donkey', 'cat', 'cow', 'horse']

How would you turn it into this one:

{ 'd' => ['dog', 'donkey'], 'c' => ['cat', 'cow'], 'h' => ['horse'] }

Being as idiomatic as possible ?

I have tried a lot of ways, and only have gotten close, and also have seen many similar problems around, but never a solution to this one in particular,

How would you guys do it? Can you help me solve it?

Best Regards,

Upvotes: 1

Views: 2900

Answers (3)

Michael Kohl
Michael Kohl

Reputation: 66837

If you have to build your own:

animals = ['dog', 'donkey', 'cat', 'cow', 'horse']
animals.inject(Hash.new{|h,k|h[k]=[]}) { |h, animal| h[animal[0]] << animal;h} 
#=> {"d"=>["dog", "donkey"], "c"=>["cat", "cow"], "h"=>["horse"]}

Main advantage is that you only have to traverse the array once. If you find inject hard to digest, look at 1.9's each_with_object. As others pointed out they probably wanted group_by though.

Upvotes: 4

lucapette
lucapette

Reputation: 20724

Take a look at http://api.rubyonrails.org/classes/Enumerable.html#method-i-group_by. It's a core_ext in Rails. It could be used to do exactly what you have to do. Reading the source of the method you get a good example of how you can achieve that.

Upvotes: 0

Howard
Howard

Reputation: 39187

Group by the first character of your words:

['dog', 'donkey', 'cat', 'cow', 'horse'].group_by{|i|i[0]}

or being a little bit fancier:

['dog', 'donkey', 'cat', 'cow', 'horse'].group_by &:chr

Upvotes: 10

Related Questions