Question

Why doesn't this work?

puts "Hi"

x = "stop"

loop do
  a = STDIN.gets
  break if a.to_s.downcase.equal?x.to_s
end

puts "bye"
Was it helpful?

Solution

Because gets will include the Enter key used at the end of whatever you type into it.

a = gets # I type in "stop"
a == "stop\n" #=> true

In order to fix this, chop off the newline

puts "Hi"

x = "stop"

loop do
  a = STDIN.gets.chop
  break if a.to_s.downcase == x.to_s
end

puts "bye"

OTHER TIPS

There are two reasons.

First equal? is a very strong form of equality: by default it's equivalent to comparing object ids, so two strings that have the same content but aren't the same object won't be equal. You probably want to use == instead

Secondly gets will include the newline that you typed which you can remove with chop or chomp

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top