[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.
[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.
在這種情況下,可以考慮使用group_by
和count
代替:
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}
+1。它很優雅。 – sawa 2011-04-25 05:33:50
塊的返回值被用作在下一週期的備忘錄對象,所以你只要需要確保該塊返回hash
。
[1,2,2,3].inject({}) do |hash,e|
hash[e.to_s] ||= 0
hash[e.to_s] += 1
hash
end
如果您正在使用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}
在這種情況下,它是很常見的使用默認的哈希值Hash.new(..)
。
[1,2,2,3].each_with_object(Hash.new(0)){|e, hash| hash[e.to_s]+=1}
爲什麼每次在中間,而不是直接注入? – tokland 2011-04-24 16:51:09
,因爲我看到了Ruby文檔,枚舉#注入...所以我只注入枚舉只... – wizztjh 2011-04-25 07:18:59
它不是香草紅寶石,但考慮使用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