|
| 1 | +====== Option +converters+ |
| 2 | + |
| 3 | +Specifies a single field converter name or \Proc, |
| 4 | +or an \Array of field converter names and Procs. |
| 5 | + |
| 6 | +See {Field Converters}[#class-CSV-label-Field+Converters] |
| 7 | + |
| 8 | +Default value: |
| 9 | + CSV::DEFAULT_OPTIONS.fetch(:converters) # => nil |
| 10 | + |
| 11 | +The value may be a single field converter name: |
| 12 | + str = '1,2,3' |
| 13 | + # Without a converter |
| 14 | + ary = CSV.parse_line(str) |
| 15 | + ary # => ["1", "2", "3"] |
| 16 | + # With built-in converter :integer |
| 17 | + ary = CSV.parse_line(str, converters: :integer) |
| 18 | + ary # => [1, 2, 3] |
| 19 | + |
| 20 | +The value may be an \Array of field converter names: |
| 21 | + str = '1,3.14159' |
| 22 | + # Without converters |
| 23 | + ary = CSV.parse_line(str) |
| 24 | + ary # => ["1", "3.14159"] |
| 25 | + # With built-in converters |
| 26 | + ary = CSV.parse_line(str, converters: [:integer, :float]) |
| 27 | + ary # => [1, 3.14159] |
| 28 | + |
| 29 | +The value may be a \Proc custom converter: |
| 30 | + str = ' foo , bar , baz ' |
| 31 | + # Without a converter |
| 32 | + ary = CSV.parse_line(str) |
| 33 | + ary # => [" foo ", " bar ", " baz "] |
| 34 | + # With a custom converter |
| 35 | + ary = CSV.parse_line(str, converters: proc {|field| field.strip }) |
| 36 | + ary # => ["foo", "bar", "baz"] |
| 37 | + |
| 38 | +See also {Custom Converters}[#class-CSV-label-Custom+Converters] |
| 39 | + |
| 40 | +--- |
| 41 | + |
| 42 | +Raises an exception if the converter is not a converter name or a \Proc: |
| 43 | + str = 'foo,0' |
| 44 | + # Raises NoMethodError (undefined method `arity' for nil:NilClass) |
| 45 | + CSV.parse(str, converters: :foo) |
0 commit comments