解释为什么在这个Ruby脚本中抛出TypeError

时间:2015-08-17 22:40:28

标签: ruby

在此脚本中:

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让代码工作,并希望了解原因。

2 个答案:

答案 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