8000 [ruby/csv] More RDoc for field converters (#179) · kou/ruby@c9cc657 · GitHub
[go: up one dir, main page]

Skip to content

Commit c9cc657

Browse files
BurdetteLamarkou
authored andcommitted
[ruby/csv] M 8000 ore RDoc for field converters (ruby#179)
ruby/csv@2a4ef5d86a
1 parent 68035e7 commit c9cc657

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

doc/csv/recipes.rdoc

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ All code snippets on this page assume that the following has been executed:
1919
- {Convert Fields to Objects}[#label-Convert+Fields+to+Objects]
2020
- {Convert Fields to Objects Using Built-In Converters}[#label-Convert+Fields+to+Objects+Using+Built-In+Converters]
2121
- {Convert Fields to Objects Using Custom Converters}[#label-Convert+Fields+to+Objects+Using+Custom+Converters]
22+
- {Filter Field Strings}[#label-Filter+Field+Strings]
2223
- {Generating: Output Formats}[#label-Generating-3A+Output+Formats]
2324
- {Generate to String}[#label-Generate+to+String]
2425
- {Generate to String Without Headers}[#label-Generate+to+String+Without+Headers]
@@ -188,6 +189,33 @@ Output:
188189

189190
==== Convert Fields to Objects Using Custom Converters
190191

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+
191219
Define a custom field converter:
192220
strip_converter = proc {|field| field.strip }
193221

0 commit comments

Comments
 (0)
0