[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.
答案 0 :(得分:7)
块的返回值在下一个循环中用作 memo 对象,因此您只需确保该块返回hash
。
[1,2,2,3].inject({}) do |hash,e|
hash[e.to_s] ||= 0
hash[e.to_s] += 1
hash
end
答案 1 :(得分:4)
在这种情况下,请考虑使用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}
答案 2 :(得分: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}
答案 3 :(得分:2)
在这种情况下,使用默认哈希值Hash.new(..)
非常常见。
[1,2,2,3].each_with_object(Hash.new(0)){|e, hash| hash[e.to_s]+=1}