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

前端 未结 3 1788
不知归路
不知归路 2020-12-15 12:00

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

side question:

相关标签:
3条回答
  • 2020-12-15 12:27

    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.

    0 讨论(0)
  • 2020-12-15 12:31

    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.

    0 讨论(0)
  • 2020-12-15 12:47

    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.

    0 讨论(0)
提交回复
热议问题