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


Ruby Row.fields用法及代碼示例

本文簡要介紹ruby語言中 CSV::Row.fields 的用法。

用法

fields(*specifiers)
也別名為:values_at

根據給定的 specifiers 返回字段值,可以是以下的任何混合:

  • 整數索引。

  • 整數索引的範圍。

  • 包含標題和偏移量的 2 元素數組。

  • 標題。

  • 標題範圍。

對於上述前四種情況之一的specifier,返回self.field(specifier)的結果;見 field

盡管可能有任意數量的 specifiers ,但此處的示例將一次說明一個。

當說明符是整數 index 時,返回 self.field(index) L

source = "Name,Name,Name\nFoo,Bar,Baz\n"
table = CSV.parse(source, headers: true)
row = table[0]
row.fields(1) # => ["Bar"]

當說明符是整數範圍 range 時,返回 self.field(range)

row.fields(1..2) # => ["Bar", "Baz"]

當說明符是 2 元素數組 array 時,返回 self.field(array) L

row.fields('Name', 1) # => ["Foo", "Bar"]

當說明符是標頭 header 時,返回 self.field(header) L

row.fields('Name') # => ["Foo"]

當說明符是標頭範圍 range 時,從 range.startrange.end 的索引形成一個新的 Range new_range ,並返回 self.field(new_range)

source = "Name,NAME,name\nFoo,Bar,Baz\n"
table = CSV.parse(source, headers: true)
row = table[0]
row.fields('Name'..'NAME') # => ["Foo", "Bar"]

如果沒有給出參數,則返回所有字段:

row.fields # => ["Foo", "Bar", "Baz"]

相關用法


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