Search code examples
rubyinputstdoutstdinchomp

Difference between ways to use gets method


I saw two ways to use gets, a simple form:

print 'Insert your name: '
name = gets()
puts "Your name is #{name}"

and a form that drew my attention:

print 'Insert your name: '
STDOUT.flush
name = gets.chomp
puts "Your name is #{name}"

The second sample looks like perl in using the flush method of the default output stream. Perl makes explicit default output stream manipulating; the method flush is a mystery to me. It can behave different from what I'm inferring, and it uses chomp to remove the new line character.

What happens behind the scenes in the second form? What situation is it useful or necessary to use the second form?


Solution

  • "Flushing" the output ensures that it shows the printed message before it waits for your input; this may be just someone being certain unnecessarily, or it may be that on certain operating systems you need it. Alternatively you can use STDOUT.sync = true to force a flush after every output. (You may wonder, "Why wouldn't I always use this?" Well, if your code is outputting a lot of content, repeatedly flushing it may slow it down.)

    chomp removes the newline from the end of the input. If you want the newline (the result of the user pressing "Enter" after typing their name) then don't chomp it.