このマニュアルは既にメンテナンスが終了したバージョンの Ruby を対象としています。 最新版のマニュアルへ

Ruby 3.1 リファレンスマニュアル

instance method ARGF.class#gets

gets(rs = $/, chomp: false) -> String | nil[permalink][rdoc][edit]
gets(limit, chomp: false) -> String | nil
gets(rs, limit, chomp: false) -> String | nil

ARGFの現在位置から一行ずつ文字列として読み込みます。EOF に到達した時には nil を返します。

[PARAM] rs:
行の区切りを文字列で指定します。rs に nil を指定すると行区切りなしとみなします。空文字列 "" を指定すると連続する改行を行の区切りとみなします(パラグラフモード)。
[PARAM] limit:
最大の読み込みバイト数
[PARAM] chomp:
true を指定すると各行の末尾から "\n", "\r", または "\r\n" を取り除きます。
# $ echo "line1\nline2\nline3\n\nline4\n" > test.txt
# $ ruby test.rb test.txt

# test.rb
p ARGF.gets                # => "line1\n"
# $ echo "line1\nline2\nline3\n\nline4\n" > test.txt
# $ ruby test.rb test.txt

# test.rb
p ARGF.gets(2)                # => "li"
# $ echo "line1\nline2\nline3\n\nline4\n" > test.txt
# $ ruby test.rb test.txt

# test.rb
p ARGF.gets("e")                # => "line"
# $ echo "line1\nline2\nline3\n\nline4\n" > test.txt
# $ ruby test.rb test.txt

# test.rb
p ARGF.gets("")                # => "line1\nline2\nline3\n\n"

[SEE_ALSO] Kernel.#gets, IO#gets, ARGF.class#getbyte, ARGF.class#getc