2012-11-28 113 views
0

我一直在使用arel/rails,並想出瞭如何讓我的group by statement正常工作。使用多列它給出這樣的輸出作爲數組的密鑰散列 - 如何變成一個正常的散列?

{["column1_value","column2_value","column3_value"]=>count,... etc ...} 

什麼是最好的/最簡單的方法來將其轉換爲多級哈希?例如

{column1_value:{ 
    column2_value:{ 
    column3_value1: count, 
    column3_value2: count 
    } 
    column2_value2:{ ...} 
} 
column2_value2: {....} 
} 

我得到爲什麼結果是由數組鍵入的,但它並不是特別容易使用!

+2

'group_by'是外部AREL。如果它沒有產生預期的結果,你可以隨時做自己的分組。 – tadman

回答

2

或者,如果你喜歡的迭代方法:

a = {[:a, :b, :c]=> 1, [:a, :b, :d]=>2, [:a, :c, :e]=>3} 

a.each_with_object({}) { |((*keys, l), v), m| 
    keys.inject(m) {|mm, key| 
    mm[key] ||= {} 
    }[l] = v 
} 
# {:a=>{:b=>{:c=>1, :d=>2}, :c=>{:e=>3}}} 
+0

哇,這相當不錯!謝謝 :) –

1
def hashify(array, value, hash) 
    key = array.shift 
    if array.empty? 
    hash[key] = value 
    else 
    hashify(array, value, hash[key] ||= {}) 
    end 
end 

a = {[:a, :b, :c]=> 1, [:a, :b, :d]=>2, [:a, :c, :e]=>3} 
h = {} 
a.each { |k, v| hashify(k, v, h) } 

h 
# => {:a=>{:b=>{:c=>1, :d=>2}, :c=>{:e=>3}}} 
+0

也是一個很好的答案。我希望我能接受兩個。我會接受迭代的,就像我喜歡遞歸一樣,爲這個案例定義一個方法似乎過分了。 –

相關問題