Sel*_*lah 5 ruby arrays inject
我正在尝试计算数组中元素的出现次数并将其保存在哈希中.我想使用注入功能.我有这个代码:
a = ["the","the","a", "it", "it", "it"]
a.inject(Hash.new(0)) {|hash,word| hash[word] += 1}
Run Code Online (Sandbox Code Playgroud)
我不明白为什么会出现以下错误:
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'
Run Code Online (Sandbox Code Playgroud)
另外,我不知道如何解决它.
inject使用两个参数memo和current元素调用块.然后它获取块的返回值并用它替换备忘录.您的块返回整数.因此,在第一次迭代后,您的备忘录不再是哈希值,它是一个整数.并且整数不接受索引器中的字符串.
修复很简单,只需从块返回哈希.
a = ["the","the","a", "it", "it", "it"]
a.inject(Hash.new(0)) {|hash,word| hash[word] += 1; hash }
Run Code Online (Sandbox Code Playgroud)
您可能更喜欢,each_with_object因为它不会替换备忘录.请注意,each_with_object接受反向参数(元素优先,备忘录秒).
a.each_with_object(Hash.new(0)) {|word, hash| hash[word] += 1}
Run Code Online (Sandbox Code Playgroud)