我正在尝试计算数组中元素的出现次数并将其保存在散列中。我想使用注入(inject)功能。我有这段代码:
a = ["the","the","a", "it", "it", "it"]
a.inject(Hash.new(0)) {|hash,word| hash[word] += 1}
我不明白为什么会出现以下错误:
TypeError: can't convert String into Integer
from (irb):47:in `[]'
from (irb):47:in `block in irb_binding'
from (irb):47:in `each'
from (irb):47:in `inject'
另外,我不知道如何修复它。
最佳答案
inject
使用两个参数调用您的 block ,memo 和当前元素。然后它获取 block 的返回值并用它替换 memo。您的 block 返回整数。因此,在第一次迭代之后,您的备忘录不再是散列,而是一个整数。整数在其索引器中不接受字符串。
修复很简单,只需从 block 中返回哈希即可。
a = ["the","the","a", "it", "it", "it"]
a.inject(Hash.new(0)) {|hash,word| hash[word] += 1; hash }
您可能更喜欢 each_with_object
,因为它不会取代备忘录。请注意,each_with_object
接受相反的参数(元素在前,备忘录在后)。
a.each_with_object(Hash.new(0)) {|word, hash| hash[word] += 1}
关于ruby - 使用注入(inject)来计算数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16860703/