本文簡要介紹ruby語言中 CSV.parse_line
的用法。
用法
parse_line(string) → new_array or nil
parse_line(io) → new_array or nil
parse_line(string, **options) → new_array or nil
parse_line(io, **options) → new_array or nil
parse_line(string, headers: true, **options) → csv_row or nil
parse_line(io, headers: true, **options) → csv_row or nil
返回通過使用指定的 options
解析 string
或 io
的第一行創建的數據。
-
參數
string
應該是一個字符串對象;它將被放入位於開頭的新StringIO
對象中。 -
參數
io
應該是一個IO
對象,即:-
開放閱讀;返回時,
IO
對象將被關閉。 -
定位在開頭。要定位在末尾,要追加,請使用方法
CSV.generate
。對於任何其他定位,請改為傳遞預設的 StringIO 對象。
-
-
參數
options
:請參閱解析選項
沒有選項headers
如果沒有選項 headers
,則將第一行作為新數組返回。
這些示例假定事先執行:
string = "foo,0\nbar,1\nbaz,2\n"
path = 't.csv'
File.write(path, string)
解析 String 對象的第一行:
CSV.parse_line(string) # => ["foo", "0"]
解析 File
對象的第一行:
File.open(path) do |file|
CSV.parse_line(file) # => ["foo", "0"]
end # => ["foo", "0"]
如果參數是空字符串,則返回 nil
:
CSV.parse_line('') # => nil
使用選項headers
使用 {option headers
},將第一行作為 CSV::Row
對象返回。
這些示例假定事先執行:
string = "Name,Count\nfoo,0\nbar,1\nbaz,2\n"
path = 't.csv'
File.write(path, string)
解析 String 對象的第一行:
CSV.parse_line(string, headers: true) # => #<CSV::Row "Name":"foo" "Count":"0">
解析 File
對象的第一行:
File.open(path) do |file|
CSV.parse_line(file, headers: true)
end # => #<CSV::Row "Name":"foo" "Count":"0">
如果參數是 nil
則引發異常:
# Raises ArgumentError (Cannot parse nil as CSV):
CSV.parse_line(nil)
相關用法
- Ruby CSV.parse用法及代碼示例
- 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_line。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。