Reputation: 506
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?
Upvotes: 0
Views: 187
Reputation: 8424
Looking at some Github code I can see that STDOUT.flush
is used mostly for server-side/multi-threaded jobs, and not in everyday use.
Generally speaking, when you want to accept input from the user, you'd want to use gets.chomp
. Just remember, no matter what the user enters, Ruby will ALWAYS interprete that as a string.
To convert it to an integer, you need to call to_i
, or to_f
for a float. You don't need chomp
in these cases, since to_i
or to_f
removes the "\n" automatically. There are a lot of subtle things going on implicitly as you'll see, and figuring them out is simply a matter of practice.
Upvotes: 2
Reputation: 31
I've rarely seen someone use STDOUT.flush except in mutli-threading. Also it makes things confusing, defeating the whole purpose of writing elegant code.
Upvotes: 1
Reputation: 303188
"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.
Upvotes: 2