我怎样才能将这个哈希数组分组? [英] How can I group this array of hashes?
本文介绍了我怎样才能将这个哈希数组分组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的散列数组:
- :name:Ben
:age:18
- :姓名:David
:年龄:19
- :姓名:Sam
:年龄:18
我需要按照 age
将它们分组,所以它们最终会像这样:
18:
- :姓名:Ben
:年龄:18
- :姓名:Sam
:年龄:18
19:
- :姓名:David
:年龄:19
我试过这样做:
array = array.group_by&:age
但是我得到这个错误:
NoMethodError (对于{:name =>Ben,:age => 18},未定义的方法`age':哈希):
我做错了什么?我使用的是Rails 3.0.1和Ruby 1.9.2
解决方案 &:age 意味着
group_by
方法应该调用项目上的 age
方法来获取组数据。这个 age
方法没有在Hashes项目中定义。 这应该可以工作:
array.group_by {| d | d [:age]}
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
解决方案
The &:age
means that the group_by
method should call the age
method on the items to get the group by data. This age
method is not defined on the items which are Hashes.
This should work:
array.group_by { |d| d[:age] }
这篇关于我怎样才能将这个哈希数组分组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文