ruby-changes:63729
From: Burdette <ko1@a...>
Date: Tue, 24 Nov 2020 09:34:38 +0900 (JST)
Subject: [ruby-changes:63729] 76e5e5aaec (master): [ruby/csv] More RDoc for field converters (#179)
https://git.ruby-lang.org/ruby.git/commit/?id=76e5e5aaec From 76e5e5aaec9eb0ec83eb32831a4df4203c24a0a9 Mon Sep 17 00:00:00 2001 From: Burdette Lamar <BurdetteLamar@Y...> Date: Wed, 23 Sep 2020 16:43:41 -0500 Subject: [ruby/csv] More RDoc for field converters (#179) https://github.com/ruby/csv/commit/2a4ef5d86a diff --git a/doc/csv/recipes.rdoc b/doc/csv/recipes.rdoc index 20c4c4b..be75ded 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: https://github.com/ruby/ruby/blob/trunk/doc/csv/recipes.rdoc#L19 - {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: https://github.com/ruby/ruby/blob/trunk/doc/csv/recipes.rdoc#L189 ==== 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 } -- cgit v0.10.2 -- ML: ruby-changes@q... Info: http://www.atdot.net/~ko1/quickml/