简体   繁体   中英

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

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

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.

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.

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 (ie, stdin) in such a situation, you have to use it STDIN.gets explicitly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM