I'm a total beginner in ruby but I can't get out of this issue I get these when I run the code, it all works well until the end:
INPUT TEXT: It all works well until
INPUT SUBTEXT: ll
TEXT: It all works well until SUBTEXT: ll
OUTPUT: 4 15
undefined method +' for nil:NilClass (repl):18:in
initialize'
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
In Ruby, String#index
doesn't return -1 when the substring is not found; it returns nil
. Change your condition from while i != -1
to while i
. (This works because, unlike some other languages, Ruby considers the value 0 to be true; only false
and nil
are false.)
Index return nil if substrings doesn't exist. So this should solve this issue
@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
puts i.to_s + ' '
i = @text.index @subtext, i+1
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.