Ruby的nil:NilClass未定义方法`+'

玉盒

我是红宝石的初学者,但是我无法摆脱这个问题,我在运行代码时得到了这些,直到最后一切都很好:

输入文字:一切正常,直到

输入文字:ll

文字:直到SUBTEXT:ll为止一切正常

输出:4 15

未定义的方法+' for nil:NilClass (repl):18:in初始化'

   puts "\nINPUT TEXT:"
    @text =  gets.chomp

puts "\nINPUT SUBTEXT:" 
    @subtext = gets.chomp

    puts "\nTEXT: " + @text
    puts "SUBTEXT: " + @subtext
    puts "\n"
    i = @text.index (@subtext)

    puts "OUTPUT:"

    while i != -1
            puts  i.to_s + ' '
            i = @text.index @subtext, i+1
    end
马克·里德

在Ruby中,String#index未找到子字符串时不返回-1;它返回nil将您的条件从更改while i != -1while i(之所以起作用,是因为与其他语言不同,Ruby认为值0为true;只有falseandnil为false。)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章