Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Until loop doesn't work as expected

Tags:

ruby

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?

like image 813
nanuqcz Avatar asked Mar 01 '26 00:03

nanuqcz


1 Answers

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).

like image 175
Cristian Lupascu Avatar answered Mar 03 '26 15:03

Cristian Lupascu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!