没有从nil到整数的隐式转换 [英] No implicit conversion from nil to integer

查看:109
本文介绍了没有从nil到整数的隐式转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串数组,这些字符串是采用html并使用split函数创建的.我正在尝试通过以下方式进行迭代:

I have an array of strings created from taking html and using the split function. I am trying to iterate through it with:

html_array.each do |line|
    ...
end

我可以使用puts line.index('text')在每个line中的字符串索引puts,并且可以使用puts line[17]在索引中的字符puts(都不打印nil),但是当我合并时像

I can puts the index of a string within each line with puts line.index('text'), and I can puts the character at an index with puts line[17] (neither of which print nil), but when I combine the two into one command like

puts line[line.index('text')]

它给了我错误:

no implicit conversion from nil to integer (TypeError)

有人可以告诉我我做错了什么吗?我是编程和ruby btw的新手.

Can somebody please tell me what I am doing wrong? I am new to programming and ruby btw.

推荐答案

line.index('text')在某个时候返回nil,因为在该行中找不到字符串"text".然后,您尝试访问line[nil],它是无效的数组索引.

line.index('text') is returning nil at some point, because the string "text" can't be found in the line. You are then attempting to access line[nil], which is an invalid array index.

像这样的事情可能会更好:

Something like this might be better:

index = line.index('text')
if index.nil?
  puts "Text not found"
else
  puts line[index]
end

这将在尝试使用该字符串之前检查它的索引是否为nil(并且如果该行不包含该字符串,则会提醒您).

This will check to see if the index of the string is nil before attempting to use it (and will alert you if the line did not contain the string).

这篇关于没有从nil到整数的隐式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆