diff options
author | Burdette Lamar <BurdetteLamar@Yahoo.com> | 2020-09-23 16:43:41 -0500 |
---|---|---|
committer | Sutou Kouhei <kou@cozmixng.org> | 2020-11-24 09:33:55 +0900 |
commit | 76e5e5aaec9eb0ec83eb32831a4df4203c24a0a9 (patch) | |
tree | 75f4a40228af5dc262d9034b8acf32ede1b1a7ff | |
parent | 5a0c8068c8b370c2ce2ba411c146a80194eb3516 (diff) | |
download | ruby-76e5e5aaec9eb0ec83eb32831a4df4203c24a0a9.tar.gz |
[ruby/csv] More RDoc for field converters (#179)
https://github.com/ruby/csv/commit/2a4ef5d86a
-rw-r--r-- | doc/csv/recipes.rdoc | 28 |
1 files changed, 28 insertions, 0 deletions
diff --git a/doc/csv/recipes.rdoc b/doc/csv/recipes.rdoc index 20c4c4b66a..be75ded300 100644 --- a/doc/csv/recipes.rdoc +++ b/doc/csv/recipes.rdoc @@ -19,6 +19,7 @@ All code snippets on this page assume that the following has been executed: - {Convert Fields to Objects}[#label-Convert+Fields+to+Objects] - {Convert Fields to Objects Using Built-In Converters}[#label-Convert+Fields+to+Objects+Using+Built-In+Converters] - {Convert Fields to Objects Using Custom Converters}[#label-Convert+Fields+to+Objects+Using+Custom+Converters] + - {Filter Field Strings}[#label-Filter+Field+Strings] - {Generating: Output Formats}[#label-Generating-3A+Output+Formats] - {Generate to String}[#label-Generate+to+String] - {Generate to String Without Headers}[#label-Generate+to+String+Without+Headers] @@ -188,6 +189,33 @@ Output: ==== Convert Fields to Objects Using Custom Converters +This example defines and uses a custom field converter +that converts each column-1 value to a \Rational object. + +Define a custom field converter: + rational_converter = proc do |field, field_context| + field_context.index == 1 ? field.to_r : field + end + +Without the new converter: + string = "foo,0\nbar,1\nbaz,2\n" + array = CSV.parse(string) + array # => [["foo", "0"], ["bar", "1"], ["baz", "2"]] + +With the new converter: + array = CSV.parse(string, converters: rational_converter) + array # => [["foo", (0/1)], ["bar", (1/1)], ["baz", (2/1)]] + +You can also register a custom field converter, then refer to it by name: + CSV::Converters[:rational] = rational_converter + array = CSV.parse(string, converters: :rational) + array # => [["foo", (0/1)], ["bar", (1/1)], ["baz", (2/1)]] + +==== Filter Field Strings + +This example defines and uses a custom field converter +that strips whitespace from each field value. + Define a custom field converter: strip_converter = proc {|field| field.strip } |