Reputation: 33
Recently, i was reading legacy ruby script and hopefully to convert some of them to python.
I understand the concept of 'STDIN' and done some google search. However, there is no documentation about this stand alone statement: 'STDIN.gets.' What's the return value? Does it secretly get all the input and store it in some default places, or it is simply a piece of unfinished meaningless legacy code i should delete?
Upvotes: 2
Views: 3229
Reputation: 4950
When working with Ruby, irb
is your friend. irb is the interactive Ruby shell, or REPL. You can try your statement in irb:
2.3.0 :001 > STDIN.gets
hello
=> "hello\n"
After typing STDIN.gets
, the system waited for input. I typed hello
and then pressed the Enter key. irb indicated that the return value of the expression was "hello\n"
.
This shows that:
1) gets
returns when, and only when, the user presses Enter or equivalent.
2) gets
returns the string that was typed, pasted, etc., including the terminating Enter key.
You'll probably see a lot of calls to chomp
on strings returned by gets. This is because the trailing "\n" is rarely wanted. chomp
returns a string with the "\n" removed.
Upvotes: 1
Reputation: 87386
If you run p STDIN.method(:gets)
you get #<Method: IO#gets>
. This means that the gets
method if defined in the IO module. Knowing that, you can then read the official documentation of gets
here:
http://ruby-doc.org/core-2.3.0/IO.html#method-i-gets
The gets
method does not store its data in some default place, it returns it as the return value of the method. If that return value is being ignored, then the data is lost, but it could still be useful to call STDIN.gets
for its side effects: gets
will pause the execution of your thread and wait for input from the standard input. This would give the user a chance to review what the Ruby script has already done and terminate it early if the user wants to.
Upvotes: 2