Take the 2-minute tour ×

What's the difference between STDIN.gets() and gets.chomp() in Ruby? Aren't they both retrieving raw input from the user?

side question: If I want to convert their input into an integer, do I do

myNumb = Integer(STDIN.gets())


myNumb = Integer(gets.chomp()) 
share|improve this question
Why are you comparing one with chomp and another without? –  sawa Aug 20 '12 at 18:36
add comment

3 Answers

up vote 2 down vote accepted

Easiest way to do what you describe here is Integer(gets), since Integer() ignores the trailing newline, so chomp is unnecessary. There's also no need explicitly specify STDIN as the receiver, as that's what Kernel#gets will do if there are no arguments to the script.

share|improve this answer
add comment

gets is actually Kernel#gets. It reads from files passed as arguments or, if no arguments are present, reads from standard input. If you want to read only from standard input, then you should be more explicit about it.


As for the conversion, I normally use String#to_i. It handles newlines just fine.

share|improve this answer
But still, Integer( string ) has undeniable advantages over string.to_i. –  Boris Stitnicky Aug 20 '12 at 16:50
to_i and Integer() are very different. Personally I rather deal with an exception than getting a random 0. –  Michael Kohl Aug 20 '12 at 18:40
There are pros and cons for each method. :) –  Sergio Tulentsev Aug 20 '12 at 18:42
add comment

because if there is stuff in ARGV, the default gets method tries to treat the first one as a file and read from that. To read from the user's input (i.e., stdin) in such a situation, you have to use it STDIN.gets explicitly.

share|improve this answer
add comment

Your Answer


