在Ruby中获取数组调用的未定义方法错误

时间:2017-04-26 21:11:04

标签: arrays ruby

我的程序中有以下方法:

def crawl_urls(urlArray)
    urlArray.count.times do |i| 
        puts "now crawling site " + i.to_s + "<--------"
        has_email?(urlArray[i])
    end
end

错误消息是:

*******.rb:126:in `block in scrape_urls': undefined method `[]' for 1..2:Range (NoMethodError)

违规行,根据错误消息:

has_email?(urlArray[i])

2 个答案:

答案 0 :(得分:2)

更好的表达方式是:

def crawl_urls(urls)
  urls.each_with_index do |url, i|
    puts "now crawling site #{i} <--------"
    has_email?(url)
  end
end

没有必要times来获取偏移量,然后在each为您执行此操作时返回并查找数组中的内容。

要注意的另一件事是避免在Ruby变量或方法名称中加入大写字母。 urlArray应该是url_array,或者更好,因为它是表达它的更自然的方式,urls

答案 1 :(得分:0)

范围不是数组。在您的范围内使用.to_a进行转换,并可以使用[]