Home>

In ruby, I want to write a code that reads from the standard input one line at a time, and ends it after reading a blank line, the end of the file, and nil, but it does not work as intended.
I wrote the following code,

def input_line()
    line=gets()
    return line.chomp!
end
def input_lines()
    lines=[]
    while(line=input_line)
        if line==nil or line=='\n'# or EOF
            break
        end
        lines.push(line)
    end
end


First of all, if you enter from the keyboard, even if you type a blank line, it does not end, and you need to type Ctrl+Z to stop typing.
In the terminal of vs code, from the file,
cat data.txt | .\ruby_small_utensils.rb
If i input as, the operation will stop in the input waiting state.
In the first place, since the newline character is removed by the input_line method, while (line=input_line) becomes false if there is an empty line, I initially thought that I should not need if or less, but since it does not work, add if or less I did, but it still doesn't work.
Furthermore, if you include "or EOF" which is currently commented out, it will be said to be an uninitialized constant.

  • Answer # 1

    You should check the specifications of the method you use.

    getsButnilWill be at EOF. If it is a blank line"\n"Only line breaks.

    while(line=input_line)So in the looplineIsnilNot soif line==nilThe check is meaningless.
    Also,getsThe resultchomp!Therefore, if it is a blank line, it will be an empty string.
    chomp!I don't know whether I wrote it without understanding the meaning or forgot to write it, but the judgment of the blank line isline==""is.
    Also,'\n'When"\n"Has a different meaning, the latter is a newline character, while the former is a two-character "backslash n".

    after,input_lineamonggetsResult without checking the valuechomp!So at the time of EOFnil.chomp!Is an error.
    chomp!WhenchompLet's also check the difference between.