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

What is the difference between STDIN.gets() and gets.chomp() in Ruby? Don't they both take the original input from the user?

question: if I want to convert my input to an integer, will I do

 myNumb = Integer(STDIN.gets()) 

and

 myNumb = Integer(gets.chomp()) 
+7
source share
3 answers

The easiest way to do what you describe here is Integer(gets) , since Integer() ignores the final new line, so chomp not needed. Also, there is no need to explicitly specify STDIN as the recipient, as what "Kernel # receives" will do if there are no arguments for the script.

+3
source

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

 STDIN.gets $stdin.gets 

As for conversion, I usually use String # to_i . It does a great job with new characters.

+11
source

because if there is material in ARGV, by default the get method tries to process the first file as a file and read From it. To read from user input (i.e., Stdin) in this situation, you should use this STDIN. Is explicit.

+1
source

All Articles