我不知道是否有在紅寶石做到這一點更規範的方式的項目的屬性的對象數組1.9大廈哈希通過分組基於
我有一大堆對象的數組,我想使用數組中每個對象的屬性將它們組成一個Hash。
非常簡單的例子:
> sh = {}
=> {}
> aers = %w(a b c d ab bc de abc)
=> ["a", "b", "c", "d", "ab", "bc", "de", "abc"]
> aers.each do |aer|
> sh[aer.size] = [] if sh[aer.size].nil?
> sh[aer.size] << aer
> end
=> ["a", "b", "c", "d", "ab", "bc", "de", "abc"]
> sh
=> {1=>["a", "b", "c", "d"], 2=>["ab", "bc", "de"], 3=>["abc"]}
我想這一點,但它的輸出是錯誤的(因爲你可以看到):
sh = Hash.new([])
=> {}
> aers.each do |aer|
> sh[aer.size] << aer
> end
=> ["a", "b", "c", "d", "ab", "bc", "de", "abc"]
> sh
=> {}
而你的代碼沒有按預期工作的原因說明如下:http://stackoverflow.com/questions/2698460/strange-ruby-behavior-when-using -hash-new和here:http://stackoverflow.com/questions/2552579/ruby-method-array-not-updating-the-array-in-hash(Ruby中很常見的陷阱)。 – 2011-01-14 15:23:51