當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Ruby IO.gets用法及代碼示例

本文簡要介紹ruby語言中 IO.gets 的用法。

用法

gets(sep = $/, **getline_opts) → string or nil
gets(limit, **getline_opts) → string or nil
gets(sep, limit, **getline_opts) → string or nil

從流中讀取並返回數據;將返回值分配給 $_

如果沒有給出參數,則返回由行分隔符 $/ 確定的下一行,如果沒有則返回 nil

f = File.open('t.txt')
f.gets # => "This is line one.\n"
$_     # => "This is line one.\n"
f.gets # => "This is the second line.\n"
f.gets # => "This is the third line.\n"
f.gets # => nil

如果給出了字符串參數 sep 但沒有參數 limit ,則返回由行分隔符 sep 確定的下一行,如果沒有,則返回 nil

f = File.open('t.txt')
f.gets(' is') # => "This is"
f.gets(' is') # => " line one.\nThis is"
f.gets(' is') # => " the second line.\nThis is"
f.gets(' is') # => " the third line.\n"
f.gets(' is') # => nil

注意 sep 的兩個特殊值:

  • nil :讀取並返回整個流。

  • ''(空字符串):讀取並返回下一個“paragraph”,段落分隔符是兩個連續的行分隔符。

給定整數參數limit,最多返回limit+1字節:

# Text with 1-byte characters.
File.open('t.txt') {|f| f.gets(1) } # => "T"
File.open('t.txt') {|f| f.gets(2) } # => "Th"
File.open('t.txt') {|f| f.gets(3) } # => "Thi"
File.open('t.txt') {|f| f.gets(4) } # => "This"
# No more than one line.
File.open('t.txt') {|f| f.gets(17) } # => "This is line one."
File.open('t.txt') {|f| f.gets(18) } # => "This is line one.\n"
File.open('t.txt') {|f| f.gets(19) } # => "This is line one.\n"

# Text with 2-byte characters, which will not be split.
File.open('t.rus') {|f| f.gets(1).size } # => 1
File.open('t.rus') {|f| f.gets(2).size } # => 1
File.open('t.rus') {|f| f.gets(3).size } # => 2
File.open('t.rus') {|f| f.gets(4).size } # => 2

使用參數 seplimit ,結合上述兩種行為:

  • 返回由行分隔符 sep 確定的下一行,如果沒有則返回 nil

  • 但返回不超過 limit+1 字節。

對於上述所有形式,可以給出尾隨可選關鍵字參數;請參閱 Getline 選項:

f = File.open('t.txt')
# Chomp the lines.
f.gets(chomp: true) # => "This is line one."
f.gets(chomp: true) # => "This is the second line."
f.gets(chomp: true) # => "This is the third line."
f.gets(chomp: true) # => nil

相關用法


注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 IO.gets。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。