Ruby-on-rails 如何对这个哈希数组进行分组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7136936/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I group this array of hashes?
提问by ben
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:
我需要将它们分组age,所以它们最终是这样的:
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
我究竟做错了什么?我正在使用 Rails 3.0.1 和 Ruby 1.9.2
回答by KARASZI István
The &:agemeans that the group_bymethod should call the agemethod on the array items to get the group by data. This agemethod is not defined on the items which are Hashes in your case.
这&:age意味着该group_by方法应调用age数组项上的方法以按数据获取组。age在您的情况下,此方法未在作为哈希的项目上定义。
This should work:
这应该有效:
array.group_by { |d| d[:age] }
回答by Michael Johnston
out = {}
array_of_hashes.each do |a_hash|
out[a_hash[:age]] ||= []
out[a_hash[:age]] << a_hash
end
or
或者
array.group_by {|item| item[:age]}
回答by gunn
As others have pointed out ruby's Symbol#to_procmethod is invoked and calls the agemethod on each hash in the array. The problem here is that the hashes do not respond to an agemethod.
正如其他人指出的那样,Symbol#to_proc调用ruby 的方法并age在数组中的每个散列上调用该方法。这里的问题是散列不响应age方法。
Now we could define one for the Hash class, but we probably don't want it for every hash instance in the program. Instead we can simply define the agemethod on each hash in the array like so:
现在我们可以为 Hash 类定义一个,但我们可能不希望程序中的每个哈希实例都使用它。相反,我们可以简单地age在数组中的每个散列上定义方法,如下所示:
array.each do |hash|
class << hash
def age
self[:age]
end
end
end
And then we can use group_byjust as you were before:
然后我们可以group_by像以前一样使用:
array = array.group_by &:age

