本文簡要介紹ruby語言中 CSV.parse
的用法。
用法
parse(string) → array_of_arrays
parse(io) → array_of_arrays
parse(string, headers: ..., **options) → csv_table
parse(io, headers: ..., **options) → csv_table
parse(string, **options) {|row| ... }
parse(io, **options) {|row| ... }
使用指定的 options
解析 string
或 io
。
-
參數
string
應該是一個字符串對象;它將被放入位於開頭的新StringIO
對象中。 -
參數
io
應該是一個IO
對象,即:-
開放閱讀;返回時,
IO
對象將被關閉。 -
定位在開頭。要定位在末尾,要追加,請使用方法
CSV.generate
。對於任何其他定位,請改為傳遞預設的 StringIO 對象。
-
-
參數
options
:請參閱解析選項
沒有選項headers
沒有 {option headers
} 的情況。
這些示例假定事先執行:
string = "foo,0\nbar,1\nbaz,2\n"
path = 't.csv'
File.write(path, string)
在沒有給出塊的情況下,返回從源形成的數組數組。
解析字符串:
a_of_a = CSV.parse(string)
a_of_a # => [["foo", "0"], ["bar", "1"], ["baz", "2"]]
解析打開的文件:
a_of_a = File.open(path) do |file|
CSV.parse(file)
end
a_of_a # => [["foo", "0"], ["bar", "1"], ["baz", "2"]]
給定一個塊,調用每個已解析行的塊:
解析字符串:
CSV.parse(string) {|row| p row }
輸出:
["foo", "0"]
["bar", "1"]
["baz", "2"]
解析打開的文件:
File.open(path) do |file|
CSV.parse(file) {|row| p row }
end
輸出:
["foo", "0"]
["bar", "1"]
["baz", "2"]
使用選項headers
對於 {option headers
} 情況。
這些示例假定事先執行:
string = "Name,Count\nfoo,0\nbar,1\nbaz,2\n"
path = 't.csv'
File.write(path, string)
在沒有給出塊的情況下,返回從源形成的 CSV::Table
對象。
解析字符串:
csv_table = CSV.parse(string, headers: ['Name', 'Count'])
csv_table # => #<CSV::Table mode:col_or_row row_count:5>
解析打開的文件:
csv_table = File.open(path) do |file|
CSV.parse(file, headers: ['Name', 'Count'])
end
csv_table # => #<CSV::Table mode:col_or_row row_count:4>
在給定塊的情況下,使用每個已解析的行調用該塊,該行已形成 CSV::Row
對象:
解析字符串:
CSV.parse(string, headers: ['Name', 'Count']) {|row| p row }
輸出:
# <CSV::Row "Name":"foo" "Count":"0">
# <CSV::Row "Name":"bar" "Count":"1">
# <CSV::Row "Name":"baz" "Count":"2">
解析打開的文件:
File.open(path) do |file|
CSV.parse(file, headers: ['Name', 'Count']) {|row| p row }
end
輸出:
# <CSV::Row "Name":"foo" "Count":"0">
# <CSV::Row "Name":"bar" "Count":"1">
# <CSV::Row "Name":"baz" "Count":"2">
如果參數不是 String 對象或 IO 對象,則引發異常:
# Raises NoMethodError (undefined method `close' for :foo:Symbol)
CSV.parse(:foo)
相關用法
- Ruby CSV.parse_line用法及代碼示例
- Ruby CSV.header_convert用法及代碼示例
- Ruby CSV.skip_lines用法及代碼示例
- Ruby CSV.table用法及代碼示例
- Ruby CSV.force_quotes?用法及代碼示例
- Ruby CSV.unconverted_fields?用法及代碼示例
- Ruby CSV.generate_line用法及代碼示例
- Ruby CSV.col_sep用法及代碼示例
- Ruby CSV.shift用法及代碼示例
- Ruby CSV.skip_blanks?用法及代碼示例
- Ruby CSV.read用法及代碼示例
- Ruby CSV.row_sep用法及代碼示例
- Ruby CSV.header_row?用法及代碼示例
- Ruby CSV.headers用法及代碼示例
- Ruby CSV.csv << row用法及代碼示例
- Ruby CSV.encoding用法及代碼示例
- Ruby CSV.each用法及代碼示例
- Ruby CSV.return_headers?用法及代碼示例
- Ruby CSV.converters用法及代碼示例
- Ruby CSV.line用法及代碼示例
- Ruby CSV.convert用法及代碼示例
- Ruby CSV.line_no用法及代碼示例
- Ruby CSV.instance用法及代碼示例
- Ruby CSV.liberal_parsing?用法及代碼示例
- Ruby CSV.new用法及代碼示例
注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 CSV.parse。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。