Using gets() gives “No such file or directory” error when I pass arguments to my script

前端 未结 2 1246
独厮守ぢ
独厮守ぢ 2020-12-29 00:50

Hi I am making a simple ruby script practiced where I make a form using gets.chomp and arguments, the problem is that when gets.chomp use the scrip

相关标签:
2条回答
  • 2020-12-29 01:46

    It looks like you want to the user to type some input by reading a line from STDIN, the best way to do this is by calling STDIN.gets and not gets. So your line becomes:

    word = STDIN.gets.chomp
    

    This is documented as IO.gets. STDIN is an instance of IO.

    Right now, you're executing Kernel.gets, which does something different (emphasis mine):

    Returns (and assigns to $_) the next line from the list of files in ARGV (or $*), or from standard input if no files are present on the command line.

    This appears to behave like STDIN.gets if ARGV is empty, but is not the same thing, hence the confusion.

    0 讨论(0)
  • 2020-12-29 01:46

    If your program handle empty argument nor non-empty argument. You can use this module (especially if you already use default gets everywhere)

    # A module that help to use method gets no matter what the file argument is
    module InputHelper
        # Handle input method based on its file argument
        def gets
            if ARGV.nil?
                Kernel.gets
            else
                STDIN.gets
            end
        end
    end
    

    and then you could include it on your class

    require 'input_helper'
    class YourClass
        ...
        include InputHelper
        ...
    end
    
    0 讨论(0)
提交回复
热议问题