문제

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"
도움이 되었습니까?

해결책

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"

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top