2011-04-24 28 views
0
[1,2,2,3].each.inject({}){|hash,e| 
    hash[e.to_s]||=0 
    hash[e.to_s]+=1 
} 

它返回類型錯誤:不能轉換成字符串整數錯誤,而使用注射

TypeError: can't convert String into Integer. 
+2

爲什麼每次在中間,而不是直接注入? – tokland 2011-04-24 16:51:09

+0

,因爲我看到了Ruby文檔,枚舉#注入...所以我只注入枚舉只... – wizztjh 2011-04-25 07:18:59

+1

它不是香草紅寶石,但考慮使用Facets,這是一個很酷的圖書館:http://rubyworks.github.com/刻面/ DOC/API /型芯/ Enumerable.html#頻方法。 [1,2,2,3] .frequency#=> {1 => 1,2 => 2,3 => 1} – tokland 2011-04-25 07:58:52

回答

4

在這種情況下,可以考慮使用group_bycount代替:

arr = [1,2,2,3] 
throwaway_hash = arr.group_by{|x| x} 
result_hash = Hash[throwaway_hash.map{|value, values| [value, values.count]}] 
# => {1=>1, 2=>2, 3=>1} 
+0

+1。它很優雅。 – sawa 2011-04-25 05:33:50

7

塊的返回值被用作在下一週期的備忘錄對象,所以你只要需要確保該塊返回hash

[1,2,2,3].inject({}) do |hash,e| 
    hash[e.to_s] ||= 0 
    hash[e.to_s] += 1 
    hash 
end 
2

如果您正在使用1.9可以使用each_with_object代替inject(注意逆參數順序):

[1,2,2,3].each_with_object({}) do |e, hash| 
    hash[e.to_s]||=0 
    hash[e.to_s]+=1 
end 
#=> {"1"=>1, "2"=>2, "3"=>1} 
2

在這種情況下,它是很常見的使用默認的哈希值Hash.new(..)

[1,2,2,3].each_with_object(Hash.new(0)){|e, hash| hash[e.to_s]+=1} 
相關問題