开发者

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 exa开发者_如何转开发ctly 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,


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜