Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions doc/csv/recipes.rdoc
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
== Recipes

All code snippets on this page assume that the following has been executed:
require 'csv'

=== Contents

- {Parsing: Source Formats}[#label-Parsing-3A+Source+Formats]
Expand All @@ -12,6 +15,10 @@
- {Parse from IO Stream}[#label-Parse+from+IO+Stream]
- {Parse from IO Stream Without Headers}[#label-Parse+from+IO+Stream+Without+Headers]
- {Parse from IO Stream with Headers}[#label-Parse+from+IO+Stream+with+Headers]
- {Parsing: Field Converters}[#label-Parsing-3A+Field+Converters]
- {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]
- {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]
Expand Down Expand Up @@ -152,6 +159,52 @@ Output:
#<CSV::Row "Name":"bar" "Value":"1">
#<CSV::Row "Name":"baz" "Value":"2">

=== Parsing: Field Converters

==== Convert Fields to Objects

Use field converters to change parsed Strings into other, more specific, object.

==== Convert Fields to Objects Using Built-In Converters

Without converters (all fields parsed as Strings):
source = "0,1.1,2020-09-19"
parsed = CSV.parse(source)
parsed # => [["0", "1.1", "2020-09-19"]]
parsed.first.each {|field| p field.class }
Output:
String
String
String

With built-in converters (see {Built-In Field Converters}[../../CSV.html#class-CSV-label-Built-In+Field+Converters]):
parsed = CSV.parse(source, converters: :all)
parsed # => [[0, 1.1, #<DateTime: 2020-09-19T00:00:00+00:00 ((2459112j,0s,0n),+0s,2299161j)>]]
parsed.first.each {|field| p field.class }
Output:
Integer
Float
DateTime

==== Convert Fields to Objects Using Custom Converters

Define a custom field converter:
strip_converter = proc {|field| field.strip }

Without the new converter:
string = " foo , 0 \n bar , 1 \n baz , 2 \n"
array = CSV.parse(string)
array # => [[" foo ", " 0 "], [" bar ", " 1 "], [" baz ", " 2 "]]

With the new converter:
array = CSV.parse(string, converters: strip_converter)
array # => [["foo", "0"], ["bar", "1"], ["baz", "2"]]

You can also register a custom field converter, then refer to it by name:
CSV::Converters[:strip] = strip_converter
array = CSV.parse(string, converters: :strip)
array # => [["foo", "0"], ["bar", "1"], ["baz", "2"]]

=== Generating: Output Formats

==== Generate to \String Without Headers
Expand Down