Home > front end >  Ruby returning "goodbye" unexpectedly
Ruby returning "goodbye" unexpectedly

Time:12-29

So I wrote this code:

while true
  text = gets
  if text == "goodbye"
    puts "goodbye"
    break
  end
end

(I wrote it with indentation) And when I type: Hello It returns "goodbye" and the loop keeps on going? Could somebody explain why? And how to fix it?

I typed "goodbye" it returns "goodbye" and keeps on going.

CodePudding user response:

You likely need to use gets.chomp because it will include a \n character on the string. I recommend you use binding.pry for debugging things like this

CodePudding user response:

I think you should take in count that gets catches the "\n".

So you can use:

break if text.include?('goodbye')

or

break if text.chomp.eql?('goodbye')
  • Related