在此脚本中:
dictionary = [
"below","down","go","going","horn","how","howdy","it","i","low","own","part",
"partner","sit"
]
def substrings(string, dictionary)
frequencies = Hash.new(0)
dictionary.each_index do |substring|
frequencies.store(dictionary.fetch(substring), string.scan(/#{dictionary[substring]}/i).length)
end
frequencies.each_pair {|word, count| puts "#{word} => #{count}"}
end
substrings("Howdy partner, sit down! How's it going?", dictionary)
如果我将dictionary.each_index
更改为dictionary.each
,则会收到以下错误:
in `fetch': no implicit conversion of String into Integer (TypeError)"
请解释原因。我知道each
返回数组的值,而each_index
返回索引。我无法使用each
让代码工作,并希望了解原因。
答案 0 :(得分:2)
dictionary
是一个数组。 Array#fetch
期望一个数字索引,并将获取该索引处的值。如果您使用dictionary.each
,那么substring
将成为一个字符串(即,下方,下方,去,去,号角等),这不是该方法的有效参数。
each_index
有效,因为substring
是一个整数(数组的索引)。
答案 1 :(得分:2)
Array#each_index遍历每个数组。这意味着,对于您的dictionary
数组,substring
变量将设置为0
,然后设置为1
,然后设置为2
等。其中每个值均为一个整数。
Array#fetch期望一个Integer作为它的参数,并返回数组中该索引处的值。使用each
时,您传递的是实际的字符串值而不是索引。因此,你看到的错误。
如果您想使用Array#each,则需要像这样更新each
块。
dictionary.each do |substring|
frequencies.store(substring, string.scan(/#{substring}/i).length)
end