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())
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.
“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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With