nanuqcz nanuqcz - 2 months ago 7
Ruby Question

Ruby: Until loop doesn't work as expected

I just wrote this simple script:

#!/bin/env ruby

begin
print "Continue? [Y/n] "
key = gets
end until key == 'n'


I expect that if I hit "n" key, the loop will end. But that's not happening. No matter what key I send, loop always continue:
until loop problem

What am I doing wrong?

Answer

gets also captures the ENTER you press after the n.

Try key = gets.chomp instead (see the explanation here: http://ruby-doc.org/docs/Tutorial/part_02/user_input.html#newline).

Comments