@@ -19,6 +19,7 @@ All code snippets on this page assume that the following has been executed:
19
19
- {Convert Fields to Objects}[#label-Convert+Fields+to+Objects]
20
20
- {Convert Fields to Objects Using Built-In Converters}[#label-Convert+Fields+to+Objects+Using+Built-In+Converters]
21
21
- {Convert Fields to Objects Using Custom Converters}[#label-Convert+Fields+to+Objects+Using+Custom+Converters]
22
+ - {Filter Field Strings}[#label-Filter+Field+Strings]
22
23
- {Generating: Output Formats}[#label-Generating-3A+Output+Formats]
23
24
- {Generate to String}[#label-Generate+to+String]
24
25
- {Generate to String Without Headers}[#label-Generate+to+String+Without+Headers]
@@ -188,6 +189,33 @@ Output:
188
189
189
190
==== Convert Fields to Objects Using Custom Converters
190
191
192
+ This example defines and uses a custom field converter
193
+ that converts each column-1 value to a \Rational object.
194
+
195
+ Define a custom field converter:
196
+ rational_converter = proc do |field, field_context|
197
+ field_context.index == 1 ? field.to_r : field
198
+ end
199
+
200
+ Without the new converter:
201
+ string = "foo,0\nbar,1\nbaz,2\n"
202
+ array = CSV.parse(string)
203
+ array # => [["foo", "0"], ["bar", "1"], ["baz", "2"]]
204
+
205
+ With the new converter:
206
+ array = CSV.parse(string, converters: rational_converter)
207
+ array # => [["foo", (0/1)], ["bar", (1/1)], ["baz", (2/1)]]
208
+
209
+ You can also register a custom field converter, then refer to it by name:
210
+ CSV::Converters[:rational] = rational_converter
211
+ array = CSV.parse(string, converters: :rational)
212
+ array # => [["foo", (0/1)], ["bar", (1/1)], ["baz", (2/1)]]
213
+
214
+ ==== Filter Field Strings
215
+
216
+ This example defines and uses a custom field converter
217
+ that strips whitespace from each field value.
218
+
191
219
Define a custom field converter:
192
220
strip_converter = proc {|field| field.strip }
193
221
0 commit comments