Ruby 比较错误。 a == b 正常,a > 错误乙
如果我将 == 更改为 >,我会在 ruby 中收到以下错误:比较:
nano:jc] ruby ItemController.rb
file read: snippets.txt
ItemController.rb:23:in `read': undefined method `>' for nil:NilClass (NoMethodError)
from ItemController.rb:19:in `open'
from ItemController.rb:19:in `read'
from ItemController.rb:58
以下是引起投诉的方法定义。请参阅“
if line.index("<item>") > -1
With
if line.index("<item>") == 0
it Works”行。失败并显示 > 0也。
尤克!
def read
@item_count = 0
File.open(@file_name, 'r') do |f1|
while line=f1.gets
@line.concat([line])
if line.index("<item>") > -1
puts "begin"
@item_count = @item_count + 1
end
if line.index("</item>") == 0
puts "end\n"
end
# puts line
end # while
end # do
end # def
I get the following error in ruby if I change == to > in a comparison:
nano:jc] ruby ItemController.rb
file read: snippets.txt
ItemController.rb:23:in `read': undefined method `>' for nil:NilClass (NoMethodError)
from ItemController.rb:19:in `open'
from ItemController.rb:19:in `read'
from ItemController.rb:58
Below is the method definition that is causing the complaint. See the line
if line.index("<item>") > -1
With
if line.index("<item>") == 0
it works. Fails with > 0 also .
Yuuk!
def read
@item_count = 0
File.open(@file_name, 'r') do |f1|
while line=f1.gets
@line.concat([line])
if line.index("<item>") > -1
puts "begin"
@item_count = @item_count + 1
end
if line.index("</item>") == 0
puts "end\n"
end
# puts line
end # while
end # do
end # def
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的
line.index("- ")
计算结果为nil
。 Nil 有一个==
方法,但没有>
。所以根本原因是在你没有预料到的地方出现了一个nil
。Your
line.index("<item>")
evaluates tonil
. Nil has a==
method but there is no>
. So the root cause is that there is anil
where you didn't expect it.