2011-08-21 83 views
30

我有這個數組哈希:如何分組這個哈希數組?

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

我需要將它們分組由age,所以他們最終會是這樣的:

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

我試圖做這樣說:

array = array.group_by &:age 

但我得到這個錯誤:

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

我在做什麼錯?我正在使用Rails 3.0.1和Ruby 1.9.2

回答

77

&:age意味着group_by方法應調用項目上的age方法以獲取數據組。這個age方法沒有被定義在Hashes項目上。

這應該工作:

array.group_by { |d| d[:age] } 
2
out = {} 
array_of_hashes.each do |a_hash| 
    out[a_hash[:age]] ||= [] 
    out[a_hash[:age]] << a_hash 
end 

array.group_by {|item| item[:age]} 
0

正如其他人所指出的紅寶石的Symbol#to_proc方法被調用,並呼籲陣列中的每個哈希age方法。這裏的問題是哈希不響應age方法。

現在我們可以爲Hash類定義一個,但我們可能不希望它爲程序中的每個哈希實例。相反,我們可以簡單地定義每個哈希age方法在陣列中,像這樣:

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

,然後我們可以使用group_by就像你之前:

array = array.group_by &:age