1

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"
Charles Caldwell
  • 16,649
  • 4
  • 40
  • 47
darkspine
  • 651
  • 1
  • 6
  • 17
  • You don't need to use `to_s` for `a.to_s` or `x.to_s` as both are Strings and will always be, even when read from the keyboard. – the Tin Man Jul 10 '12 at 18:53

2 Answers2

3

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"
Charles Caldwell
  • 16,649
  • 4
  • 40
  • 47
1

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

Frederick Cheung
  • 83,189
  • 8
  • 152
  • 174