简体   繁体   English

如何对这个哈希数组进行分组?

[英]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: 我需要按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

The &:age means that the group_by method should call the age method on the array items to get the group by data. &:age表示group_by方法应该调用数组项上的age方法以按数据获取组。 This age method is not defined on the items which are Hashes in your case. 对于您的案例中的哈希项,未定义此age方法。

This should work: 这应该工作:

array.group_by { |d| d[:age] }
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]}

As others have pointed out ruby's Symbol#to_proc method is invoked and calls the age method on each hash in the array. 正如其他人指出的那样,ruby的Symbol#to_proc方法被调用,并在数组中的每个哈希上调用age方法。 The problem here is that the hashes do not respond to an age method. 这里的问题是哈希不响应age方法。

Now we could define one for the Hash class, but we probably don't want it for every hash instance in the program. 现在我们可以为Hash类定义一个,但我们可能不希望它为程序中的每个哈希实例。 Instead we can simply define the age method on each hash in the array like so: 相反,我们可以简单地在数组中的每个哈希上定义age方法,如下所示:

array.each do |hash|
  class << hash
    def age
      self[:age]
    end
  end
end

And then we can use group_by just as you were before: 然后我们可以像以前一样使用group_by

array = array.group_by &:age

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM