Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
解释为什么在这个Ruby脚本中抛出TypeError_Ruby - Fatal编程技术网

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

解释为什么在这个Ruby脚本中抛出TypeError,ruby,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(dic

在此脚本中:

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_索引更改为dictionary.each,则会出现以下错误:

in `fetch': no implicit conversion of String into Integer (TypeError)" 
请解释原因。我知道每个返回数组的值,每个_索引返回索引。我无法使用每种方法使代码正常工作,我想了解原因。

字典是一个数组。Arrayfetch需要一个数字索引,并将获取该索引处的值。如果使用dictionary.each,则子字符串将是一个字符串,即below、down、go、go、horn等,这不是该方法的有效参数

每个索引都可以工作,因为子字符串是一个整数,可以将索引放入数组。

遍历每个数组。这意味着对于字典数组,子字符串变量将设置为0、1、2等。这些值中的每一个都是整数

需要一个整数作为参数,并返回数组中该索引处的值。当使用each时,传递的是实际的字符串值,而不是索引。因此,您看到的错误

如果要使用,则需要像这样更新每个块

dictionary.each do|子字符串| frequencies.storesubstring,string.scan/{substring}/i.length 终止
最好在每个块之外执行string.downcase,然后执行string.scansubstring。@sawa当然,这样性能会更好。但是,我更喜欢尽可能少地修改代码,因为我的回答是,如果我尝试按照您的建议修改代码,它会抛出一个“[]”:没有将字符串隐式转换为整数TypeError。这就是为什么我首先使用不雅观的fetch方法来遍历单词。这段代码对我很有用。下面是完整代码的示例,包括我建议使用的每个代码。