本文簡要介紹ruby語言中 CSV.convert
的用法。
用法
convert(converter_name) → array_of_procs
convert {|field, field_info| ... } → array_of_procs
-
沒有塊,安裝一個現場轉換器(Proc)。
-
使用塊,定義並安裝自定義字段轉換器。
-
返回已安裝字段轉換器的數組。
-
參數
converter_name
如果給定,應該是現有字段轉換器的名稱。
請參閱現場轉換器。
沒有塊,安裝一個現場轉換器:
csv = CSV.new('')
csv.convert(:integer)
csv.convert(:float)
csv.convert(:date)
csv.converters # => [:integer, :float, :date]
如果給定,則為每個字段調用該塊:
-
參數
field
是字段值。 -
參數
field_info
是一個CSV::FieldInfo
對象,其中包含有關該字段的詳細信息。
此處的示例假定事先執行:
string = "foo,0\nbar,1\nbaz,2\n"
path = 't.csv'
File.write(path, string)
給出塊的示例:
csv = CSV.open(path)
csv.convert {|field, field_info| p [field, field_info]; field.upcase }
csv.read # => [["FOO", "0"], ["BAR", "1"], ["BAZ", "2"]]
輸出:
["foo", #<struct CSV::FieldInfo index=0, line=1, header=nil>] ["0", #<struct CSV::FieldInfo index=1, line=1, header=nil>] ["bar", #<struct CSV::FieldInfo index=0, line=2, header=nil>] ["1", #<struct CSV::FieldInfo index=1, line=2, header=nil>] ["baz", #<struct CSV::FieldInfo index=0, line=3, header=nil>] ["2", #<struct CSV::FieldInfo index=1, line=3, header=nil>]
該塊不需要返回 String 對象:
csv = CSV.open(path)
csv.convert {|field, field_info| field.to_sym }
csv.read # => [[:foo, :"0"], [:bar, :"1"], [:baz, :"2"]]
如果給出converter_name
,則不調用該塊:
csv = CSV.open(path)
csv.convert(:integer) {|field, field_info| fail 'Cannot happen' }
csv.read # => [["foo", 0], ["bar", 1], ["baz", 2]]
如果 converter_name
不是內置字段轉換器的名稱,則引發 parse-time 異常:
csv = CSV.open(path)
csv.convert(:nosuch) => [nil]
# Raises NoMethodError (undefined method `arity' for nil:NilClass)
csv.read
相關用法
- Ruby CSV.converters用法及代碼示例
- Ruby CSV.col_sep用法及代碼示例
- Ruby CSV.csv << row用法及代碼示例
- 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.shift用法及代碼示例
- Ruby CSV.skip_blanks?用法及代碼示例
- Ruby CSV.read用法及代碼示例
- Ruby CSV.row_sep用法及代碼示例
- Ruby CSV.header_row?用法及代碼示例
- Ruby CSV.headers用法及代碼示例
- Ruby CSV.encoding用法及代碼示例
- Ruby CSV.each用法及代碼示例
- Ruby CSV.return_headers?用法及代碼示例
- Ruby CSV.line用法及代碼示例
- Ruby CSV.parse_line用法及代碼示例
- Ruby CSV.parse用法及代碼示例
- Ruby CSV.line_no用法及代碼示例
- Ruby CSV.instance用法及代碼示例
- Ruby CSV.liberal_parsing?用法及代碼示例
- Ruby CSV.new用法及代碼示例
注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 CSV.convert。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。