Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

ruby on rails - How can I group this array of hashes?

I have this array of hashes:

- :name: Ben
  :age: 18
- :name: David
  :age: 19
- :name: Sam
  :age: 18

I need to group them by age, so they end up like this:

18:
- :name: Ben
  :age: 18
- :name: Sam
  :age: 18
19:
- :name: David
  :age: 19

I tried doing it this way:

array = array.group_by &:age

but I get this error:

NoMethodError (undefined method `age' for {:name=>"Ben", :age=>18}:Hash):

What am I doing wrong? I'm using Rails 3.0.1 and Ruby 1.9.2

question from:https://stackoverflow.com/questions/7136936/how-can-i-group-this-array-of-hashes

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The &:age means that the group_by method should call the age method on the array items to get the group by data. This age method is not defined on the items which are Hashes in your case.

This should work:

array.group_by { |d| d[:age] }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...