Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: What's the difference between STDIN.gets() and gets.chomp()?

Tags:

ruby

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

and

myNumb = Integer(gets.chomp()) 
like image 945
bigpotato Avatar asked Aug 20 '12 16:08

bigpotato


People also ask

What is Stdin Ruby?

The $stdin is a global variable that holds a stream for the standard input. It can be used to read input from the console. reading.rb. #!/usr/bin/ruby inp = $stdin.read puts inp. In the above code, we use the read method to read input from the console.

What does gets do in Ruby?

“gets” is a method that asks the user to input something. “chomp” is a method that removes the blank line that is automatically created by “gets” after the input.


1 Answers

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.

STDIN.gets
$stdin.gets

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

like image 54
Sergio Tulentsev Avatar answered Oct 08 '22 10:10

Sergio Tulentsev