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


Ruby Table.table[n]用法及代碼示例

本文簡要介紹ruby語言中 CSV::Table.table[n] 的用法。

用法

table[n] → row
table[range] → array_of_rows
table[header] → array_of_fields

從表中返回數據;不修改表。

表達式 table[n] ,其中 n 是一個非負整數,如果該行存在並且訪問模式為 :row:col_or_row ,則返回表的第 +n+ 行:

source = "Name,Value\nfoo,0\nbar,1\nbaz,2\n"
table = CSV.parse(source, headers: true)
table.by_row! # => #<CSV::Table mode:row row_count:4>
table[1] # => #<CSV::Row "Name":"bar" "Value":"1">
table.by_col_or_row! # => #<CSV::Table mode:col_or_row row_count:4>
table[1] # => #<CSV::Row "Name":"bar" "Value":"1">

如果 n 為負數,則從最後一行倒數:

table[-1] # => #<CSV::Row "Name":"baz" "Value":"2">

如果 n 太大或太小,則返回 nil

table[4] # => nil
table[-4] => nil

如果訪問模式是 :row 並且 n 不是 Integer-convertible object ,則引發異常。

table.by_row! # => #<CSV::Table mode:row row_count:4>
# Raises TypeError (no implicit conversion of String into Integer):
table['Name']

表達式 table[range] (其中 range Range 對象)從表中返回行,從行 range.first 開始,如果這些行存在,並且訪問模式是 :row:col_or_row

source = "Name,Value\nfoo,0\nbar,1\nbaz,2\n"
table = CSV.parse(source, headers: true)
table.by_row! # => #<CSV::Table mode:row row_count:4>
rows = table[1..2] # => #<CSV::Row "Name":"bar" "Value":"1">
rows # => [#<CSV::Row "Name":"bar" "Value":"1">, #<CSV::Row "Name":"baz" "Value":"2">]
table.by_col_or_row! # => #<CSV::Table mode:col_or_row row_count:4>
rows = table[1..2] # => #<CSV::Row "Name":"bar" "Value":"1">
rows # => [#<CSV::Row "Name":"bar" "Value":"1">, #<CSV::Row "Name":"baz" "Value":"2">]

如果行數太少,則從range.first 到最後返回所有行:

rows = table[1..50] # => #<CSV::Row "Name":"bar" "Value":"1">
rows # => [#<CSV::Row "Name":"bar" "Value":"1">, #<CSV::Row "Name":"baz" "Value":"2">]

特殊情況:如果 range.start == table.size ,返回一個空數組:

table[table.size..50] # => []

如果range.end 為負數,則從末尾計算結束索引:

rows = table[0..-1]
rows # => [#<CSV::Row "Name":"foo" "Value":"0">, #<CSV::Row "Name":"bar" "Value":"1">, #<CSV::Row "Name":"baz" "Value":"2">]

如果range.start 為負數,則從末尾計算起始索引:

rows = table[-1..2]
rows # => [#<CSV::Row "Name":"baz" "Value":"2">]

如果 range.start 大於 table.size ,則返回 nil

table[4..4] # => nil

如果列存在且訪問模式為 :col:col_or_row ,則表達式 table[header] (其中 header 是字符串)返回列值(字符串數組):

source = "Name,Value\nfoo,0\nbar,1\nbaz,2\n"
table = CSV.parse(source, headers: true)
table.by_col! # => #<CSV::Table mode:col row_count:4>
table['Name'] # => ["foo", "bar", "baz"]
table.by_col_or_row! # => #<CSV::Table mode:col_or_row row_count:4>
col = table['Name']
col # => ["foo", "bar", "baz"]

修改返回的列值不會修改表:

col[0] = 'bat'
col # => ["bat", "bar", "baz"]
table['Name'] # => ["foo", "bar", "baz"]

如果沒有這樣的列,則返回 nil 值的數組:

table['Nosuch'] # => [nil, nil, nil]

相關用法


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