### Setup for CSV Table Examples Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Sets up a string and a file path for use in CSV table examples. ```ruby string = "Name,Value\nfoo,0\nbar,1\nbaz,2\n" path = 't.csv' File.write(path, string) ``` -------------------------------- ### Setup for CSV Examples with Headers Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Sets up a string and a file path for use in CSV parsing examples with headers. ```ruby string = "Name,Count\nfoo,0\nbar,1\nbaz,2\n" path = 't.csv' File.write(path, string) ``` -------------------------------- ### Install Built-in Field Converters Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Installs built-in field converters like `:integer`, `:float`, or `:date`. Returns an array of installed converters. ```ruby csv = CSV.new('') csv.convert(:integer) csv.convert(:float) csv.convert(:date) csv.converters # => [:integer, :float, :date] ``` -------------------------------- ### Install Field Converter by Name with Block Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Installs a field converter by its name. If a block is provided, it will not be called, as the converter is already defined. ```ruby csv = CSV.open(path) csv.convert(:integer) {|field, field_info| fail 'Cannot happen' } csv.read # => [["foo", 0], ["bar", 1], ["baz", 2]] ``` -------------------------------- ### Define CSV String Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Example string input for parsing. ```ruby string = "foo,0\nbar,1\nbaz,2\n" ``` -------------------------------- ### Define input for skip_lines example Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Sets up the input string containing comments to be skipped. ```ruby str = <<-EOT # Comment foo,0 bar,1 baz,2 ``` -------------------------------- ### Define and Install Custom Field Converter Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Defines and installs a custom field converter using a block. The block is called for each field and receives the field value and a `CSV::FieldInfo` object. ```ruby string = "foo,0\nbar,1\nbaz,2\n" path = 't.csv' File.write(path, string) csv = CSV.open(path) csv.convert {|field, field_info| p [field, field_info]; field.upcase } csv.read # => [["FOO", "0"], ["BAR", "1"], ["BAZ", "2"]] ``` ```ruby csv = CSV.open(path) csv.convert {|field, field_info| field.to_sym } csv.read # => [[:foo, :"0"], [:bar, :"1"], [:baz, :"2"]] ``` -------------------------------- ### Raise ArgumentError Example Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Demonstrates an ArgumentError when trying to parse nil as CSV. ```ruby # Raises ArgumentError (Cannot parse nil as CSV): CSV.parse_line(nil) ``` -------------------------------- ### CSV encoding options Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Example of specifying encoding options for CSV parsing. ```ruby hash form: :invalid => nil # raise error on invalid byte sequence (default) :invalid => :replace # replace invalid byte sequence :undef => :replace # replace undefined conversion :replace => string # replacement string ("?" or "\uFFFD" if not specified) ``` ```ruby encoding: 'UTF-32BE:UTF-8' ``` -------------------------------- ### Get Lines to Skip - CSV::Parser Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV/Parser.html Returns the number of initial lines to skip before starting CSV parsing. This is an internal method. ```ruby def skip_lines @skip_lines end ``` -------------------------------- ### CSV Data Representation Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Example of a CSV string with row and column separators. ```text "foo,0\nbar,1\nbaz,2\n" ``` -------------------------------- ### Specify encoding for CSV.foreach Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Example of providing an encoding option to transcode data while reading. ```ruby encoding: 'UTF-32BE:UTF-8' ``` -------------------------------- ### Read lines Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV/Parser/UnoptimizedStringIO.html Delegates the gets method to the underlying StringIO object. ```ruby def gets(*args) @io.gets(*args) end ``` -------------------------------- ### Retrieve CSV rows by index Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV/Table.html Examples demonstrating how to extract rows from a CSV::Table using integers, ranges, or a combination of both. ```ruby source = "Name,Value\nfoo,0\nbar,1\nbaz,2\n" table = CSV.parse(source, headers: true) table.values_at # => [] ``` ```ruby values = table.values_at(0) values # => [#] ``` ```ruby values = table.values_at(2, 0) values # => [#, #] ``` ```ruby values = table.values_at(1..2) values # => [#, #] ``` ```ruby values = table.values_at(0..1, 1..2, 0, 2) pp values ``` -------------------------------- ### CSV Instance Method: convert Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Installs or defines field converters for the CSV object. Can be used with or without a block. ```APIDOC ## convert ### Description Installs or defines field converters for the CSV object. When called with a `converter_name`, it installs a built-in converter. When called with a block, it defines and installs a custom converter. ### Method `convert(converter_name)` or `convert {|field, field_info| ... }` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **converter_name** (Symbol) - Optional - The name of a built-in field converter to install (e.g., `:integer`, `:float`, `:date`). * **Block** - Optional - A block that takes `field` and `field_info` as arguments and returns the converted field value. ### Request Example ```ruby # Install built-in converters csv = CSV.new('') csv.convert(:integer) csv.convert(:float) # Define a custom converter csv.convert do |field, field_info| field.upcase end ``` ### Response #### Success Response (200) * **Array of Procs** - Returns an array of the currently installed field converters. #### Response Example ```ruby # Returns an array of Proc objects representing the converters. ``` ### Error Handling * Raises a parse-time exception if `converter_name` is not a recognized built-in converter. ``` -------------------------------- ### Raise NoMethodError Example Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Demonstrates a NoMethodError when trying to call 'close' on a Symbol. ```ruby # Raises NoMethodError (undefined method `close' for :foo:Symbol) CSV.parse(:foo) ``` -------------------------------- ### Field Converter with Field Info Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html A converter proc can accept a second argument, `field_info`, providing details like index, line number, and header. This example prints the arguments before stripping whitespace. ```ruby strip_converter = proc do |field, field_info| p [field, field_info] field.strip end string = " foo , 0 \n bar , 1 \n baz , 2 \n" array = CSV.parse(string, converters: strip_converter) array # => [["foo", "0"], ["bar", "1"], ["baz", "2"]] ``` -------------------------------- ### Retrieve CSV column data Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV/Table.html Examples showing how to extract specific column data from a CSV::Table using header names. ```ruby values = table.values_at('Name') values # => [["foo"], ["bar"], ["baz"]] values = table.values_at('Value', 'Name') values # => [["0", "foo"], ["1", "bar"], ["2", "baz"]] ``` -------------------------------- ### Start saving state in CSV::Parser::InputsScanner Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV/Parser/InputsScanner.html Saves the current scanner position to the internal stack. ```ruby def keep_start @keeps.push([@scanner.pos, nil]) end ``` -------------------------------- ### GET /CSV::Table/get Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV/Table.html Retrieves data from the table based on index, range, or header. ```APIDOC ## GET /CSV::Table/get ### Description Returns data from the table without modifying it. Supports indexing by row number or column header. ### Parameters #### Query Parameters - **n** (Integer|Range|String) - Required - The index, range, or header name to retrieve data for. ``` -------------------------------- ### CSV generation with multiple write converters Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Applies multiple `write_converters` in sequence. The example shows converting fields to uppercase and then to lowercase, resulting in the original case. ```ruby upcase_converter = proc {|field| field.upcase } downcase_converter = proc {|field| field.downcase } write_converters = [upcase_converter, downcase_converter] str = CSV.generate_line(['a', 'b', 'c'], write_converters: write_converters) str # => "a,b,c\n" ``` -------------------------------- ### CSV Parsing with `skip_lines` Option Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Demonstrates how to use the `skip_lines` option with `CSV.parse` to ignore lines starting with a specific character or pattern. ```APIDOC ## CSV.parse with skip_lines ### Description Parses a CSV string, skipping lines that match the provided pattern. ### Method `CSV.parse(string, **options)` ### Parameters #### Options - **skip_lines** (Regexp or String or nil) - Optional - Lines matching this pattern will be skipped. ### Request Example ```ruby str = "# Comment\nfoo,0\nbar,1\nbaz,2\n# Another comment\n" # Using a Regexp: ary = CSV.parse(str, skip_lines: /^#/) # => [["foo", "0"], ["bar", "1"], ["baz", "2"]] # Using a String: ary = CSV.parse(str, skip_lines: '#') # => [["foo", "0"], ["bar", "1"], ["baz", "2"]] ``` ### Error Handling Raises an exception if `skip_lines` is not a Regexp, String, or nil. ``` -------------------------------- ### Get the IO path Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html The `path` method returns the path of the underlying IO object if it responds to `path`. This is useful for identifying the source file. ```ruby def path @io.path if @io.respond_to?(:path) end ``` -------------------------------- ### CSV Initialization with Options Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Initializes a new CSV object with specified options. Options are fixed after creation. ```ruby def new(data = $stdout, **options) # ... implementation details ... end ``` -------------------------------- ### Initialize UnoptimizedStringIO Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV/Parser/UnoptimizedStringIO.html Creates a new instance wrapping a string in a StringIO object with binary encoding. ```ruby def initialize(string) @io = StringIO.new(string, "rb:#{string.encoding}") end ``` -------------------------------- ### Initialize CSV with Data Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/Object.html Demonstrates basic CSV parsing by passing a string to the CSV constructor and reading the data. This is useful for simple CSV strings. ```ruby CSV("CSV,data").read #=> [["CSV", "data"]] ``` -------------------------------- ### CSV Gets Alias Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html An alias for the `shift` method. ```APIDOC ## CSV.gets (Alias for shift) ### Description Alias for the `shift` method. ### Method GET ### Endpoint `csv.gets` ``` -------------------------------- ### Apply header converters Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Demonstrates various ways to apply header converters including built-in symbols, lists, and custom Procs. ```ruby str = <<-EOT Name,Value foo,0 bar,1 baz,2 EOT # With no header converter table = CSV.parse(str, headers: true) table.headers # => ["Name", "Value"] ``` ```ruby table = CSV.parse(str, headers: true, header_converters: :downcase) table.headers # => ["name", "value"] ``` ```ruby header_converters = [:downcase, :symbol] table = CSV.parse(str, headers: true, header_converters: header_converters) table.headers # => [:name, :value] ``` ```ruby upcase_converter = proc {|field| field.upcase } table = CSV.parse(str, headers: true, header_converters: upcase_converter) table.headers # => ["NAME", "VALUE"] ``` -------------------------------- ### Initialize CSV without headers Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Demonstrates CSV initialization when the headers option is not provided. ```ruby str = <<-EOT Name,Count foo,0 bar,1 bax,2 EOT csv = CSV.new(str) csv # => # csv.headers # => nil csv.shift # => ["Name", "Count"] ``` -------------------------------- ### GET /csv/read Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Reads the remaining rows from the CSV source. ```APIDOC ## GET /csv/read ### Description Forms the remaining rows from the CSV into a CSV::Table object if headers are in use, or an Array of Arrays otherwise. ### Method GET ### Endpoint /csv/read ### Response #### Success Response (200) - **data** (array/csv_table) - The parsed rows from the CSV source. ``` -------------------------------- ### Prepare File for CSV Parsing Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Create a file with CSV content for testing file-based parsing methods. ```ruby string = "foo,0\nbar,1\nbaz,2\n" path = 't.csv' File.write(path, string) ``` -------------------------------- ### GET /csv/headers Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Retrieves the headers configuration or parsed headers. ```APIDOC ## GET /csv/headers ### Description Returns the value that determines whether headers are used or the parsed headers themselves. ### Method GET ### Endpoint /csv/headers ### Response #### Success Response (200) - **headers** (object/nil) - The headers configuration or nil if not set. ``` -------------------------------- ### GET /csv/eof Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Checks if the end of the CSV file has been reached. ```APIDOC ## GET /csv/eof ### Description Returns true if the end of the CSV data has been reached, false otherwise. ### Method GET ### Response #### Success Response (200) - **eof** (boolean) - True if at end of file. ``` -------------------------------- ### Access Built-in Converter Lists Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Illustrates how to retrieve the predefined converter lists, :numeric and :all, from CSV::Converters. These provide common sets of conversion rules. ```ruby CSV::Converters[:numeric] # => [:integer, :float] CSV::Converters[:all] # => [:date_time, :numeric] ``` -------------------------------- ### GET /csv/each Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Iterates over each row in the CSV data source. ```APIDOC ## GET /csv/each ### Description Calls the provided block with each successive row of the CSV data. The source must be opened for reading. ### Method GET ### Response #### Success Response (200) - **row** (array/CSV::Row) - The current row being processed. ``` -------------------------------- ### GET /table/by_col Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV/Table.html Returns a duplicate of the table in column mode. ```APIDOC ## GET /table/by_col ### Description Creates and returns a duplicate CSV::Table object set to column mode. Useful for chaining operations without modifying the original table's mode. ### Response #### Success Response (200) - **table** (CSV::Table) - A duplicate table instance in column mode. ``` -------------------------------- ### Initialize CSV with string headers Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Parses a string to generate column headers. ```ruby str = <<-EOT foo,0 bar,1 bax,2 EOT csv = CSV.new(str, headers: 'Name,Count') csv csv.headers # => ["Name", "Count"] csv.shift # => # ``` -------------------------------- ### GET /csv/header_row? Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Checks if the CSV is configured to use header rows. ```APIDOC ## GET /csv/header_row? ### Description Returns a boolean indicating whether headers are used for parsing. ### Method GET ### Endpoint /csv/header_row? ### Response #### Success Response (200) - **result** (boolean) - True if headers are used, false otherwise. ``` -------------------------------- ### CSV Initialization Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Initializes a new CSV object. Raises ArgumentError if nil is provided as data. ```APIDOC ## CSV.new ### Description Initializes a new CSV object with the provided data and various options. Raises `ArgumentError` if `data` is `nil`. ### Method `CSV.new(data, **options)` ### Parameters - **data**: The data to parse, can be a String or an IO object. - **col_sep** (String) - Column separator (default: ",") - **row_sep** (String or Symbol) - Row separator (default: :auto) - **quote_char** (String) - Quote character (default: '"') - **field_size_limit** (Integer) - Maximum field size (default: nil) - **converters** (Array or Symbol) - Field converters (default: nil) - **unconverted_fields** (Boolean) - Keep unconverted fields (default: nil) - **headers** (Boolean or Array) - Treat first row as headers (default: false) - **return_headers** (Boolean) - Return headers as part of the data (default: false) - **write_headers** (Boolean) - Write headers when generating CSV (default: nil) - **header_converters** (Array or Symbol) - Header converters (default: nil) - **skip_blanks** (Boolean) - Skip blank lines (default: false) - **force_quotes** (Boolean) - Force quoting of all fields (default: false) - **skip_lines** (Regexp) - Skip lines matching the regex (default: nil) - **liberal_parsing** (Boolean) - Enable liberal parsing (default: false) - **internal_encoding** (String) - Internal encoding (default: nil) - **external_encoding** (String) - External encoding (default: nil) - **encoding** (String) - Encoding for input and output (default: nil) - **nil_value** (String) - Value to represent nil (default: nil) - **empty_value** (String) - Value to represent empty fields (default: "") - **quote_empty** (Boolean) - Quote empty fields (default: true) - **write_converters** (Array or Symbol) - Converters for writing (default: nil) - **write_nil_value** (String) - Nil value for writing (default: nil) - **write_empty_value** (String) - Empty value for writing (default: "") - **strip** (Boolean) - Strip whitespace from fields (default: false) ### Request Example ```ruby CSV.new(nil) ``` ### Response #### Success Response (200) Returns a new CSV object. #### Response Example ```ruby # ``` #### Error Response - **ArgumentError**: Raised if `data` is `nil`. ``` -------------------------------- ### GET /csv/header_row Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Checks if the next row to be read is a header row. ```APIDOC ## GET /csv/header_row ### Description Returns true if the next row to be read is a header row, false otherwise. ### Method GET ### Response #### Success Response (200) - **is_header** (boolean) - True if the next row is a header. ``` -------------------------------- ### Initialize CSV with nil Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Attempting to initialize a CSV object with nil raises an ArgumentError. ```ruby CSV.new(nil) ``` -------------------------------- ### CSV::InputsScanner Public Instance Methods Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV/Parser/InputsScanner.html Documentation for the public instance methods of CSV::InputsScanner. ```APIDOC ### Public Instance Methods each_line(row_separator) click to toggle source ``` ruby # File csv/parser.rb, line 96 def each_line(row_separator) buffer = nil input = @scanner.rest position = @scanner.pos offset = 0 n_row_separator_chars = row_separator.size while true input.each_line(row_separator) do |line| @scanner.pos += line.bytesize if buffer if n_row_separator_chars == 2 and buffer.end_with?(row_separator[0]) and line.start_with?(row_separator[1]) buffer << line[0] line = line[1..-1] position += buffer.bytesize + offset @scanner.pos = position offset = 0 yield(buffer) buffer = nil next if line.empty? else buffer << line line = buffer buffer = nil end end if line.end_with?(row_separator) position += line.bytesize + offset @scanner.pos = position offset = 0 yield(line) else buffer = line end end break unless read_chunk input = @scanner.rest position = @scanner.pos offset = -buffer.bytesize if buffer end yield(buffer) if buffer end ``` eos?() click to toggle source ``` ruby # File csv/parser.rb, line 163 def eos? @scanner.eos? end ``` keep_back() click to toggle source ``` ruby # File csv/parser.rb, line 181 def keep_back start, buffer = @keeps.pop if buffer string = @scanner.string keep = string.byteslice(start, string.bytesize - start) if keep and not keep.empty? @inputs.unshift(StringIO.new(keep)) @last_scanner = false end @scanner = StringScanner.new(buffer) else @scanner.pos = start end read_chunk if @scanner.eos? end ``` keep_drop() click to toggle source ``` ruby # File csv/parser.rb, line 197 def keep_drop @keeps.pop end ``` keep_end() click to toggle source ``` ruby # File csv/parser.rb, line 171 def keep_end start, buffer = @keeps.pop keep = @scanner.string.byteslice(start, @scanner.pos - start) if buffer buffer << keep keep = buffer end keep end ``` keep_start() click to toggle source ``` ruby # File csv/parser.rb, line 167 def keep_start @keeps.push([@scanner.pos, nil]) end ``` rest() click to toggle source ``` ruby # File csv/parser.rb, line 201 def rest @scanner.rest end ``` scan(pattern) click to toggle source ``` ruby # File csv/parser.rb, line 140 def scan(pattern) value = @scanner.scan(pattern) return value if @last_scanner if value read_chunk if @scanner.eos? return value else nil end end ``` scan_all(pattern) click to toggle source ``` ruby # File csv/parser.rb, line 152 def scan_all(pattern) value = @scanner.scan(pattern) return value if @last_scanner return nil if value.nil? while @scanner.eos? and read_chunk and (sub_value = @scanner.scan(pattern)) value << sub_value end value end ``` ``` -------------------------------- ### Initialize CSV with Block for Conditional Logic Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/Object.html Shows how to use a block with the CSV constructor to perform operations on the parsed data. The return value of the block becomes the return value of the CSV call. Useful for checking conditions on parsed CSV content. ```ruby CSV("CSV,data") { |c| c.read.any? { |a| a.include?("data") } } #=> true CSV("CSV,data") { |c| c.read.any? { |a| a.include?("zombies") } } #=> false ``` -------------------------------- ### Initialize CSV::Writer Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV/Writer.html Initializes a new CSV::Writer instance. Prepares the header if write_headers option is true. This is an internal class and should not be used directly. ```ruby def initialize(output, options) @output = output @options = options @lineno = 0 @fields_converter = nil prepare if @options[:write_headers] and @headers self << @headers end @fields_converter = @options[:fields_converter] end ``` -------------------------------- ### GET /csv/converters Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Returns an array containing the currently active field converters. ```APIDOC ## GET /csv/converters ### Description Returns an Array containing field converters currently registered for the CSV instance. ### Method GET ### Response #### Success Response (200) - **converters** (array) - List of active converter names or procs. ``` -------------------------------- ### Initialize CSV::Parser Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV/Parser.html Initializes a new CSV::Parser instance. This is an internal class and should not be used directly. It sets up input, options, and prepares for parsing. ```ruby def initialize(input, options) @input = input @options = options @samples = [] prepare end ``` -------------------------------- ### Get Default Converters Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Retrieves the default value for the converters option, which is nil. ```ruby CSV::DEFAULT_OPTIONS.fetch(:converters) # => nil ``` -------------------------------- ### Initialize CSV::Table Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV/Table.html Constructs a new CSV::Table from an array of CSV::Row objects. ```ruby # File csv/table.rb, line 31 def initialize(array_of_rows, headers: nil) @table = array_of_rows @headers = headers unless @headers if @table.empty? @headers = [] else @headers = @table.first.headers end end @mode = :col_or_row end ``` -------------------------------- ### Initialize CSV with array headers Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Uses the provided array elements as column headers. ```ruby str = <<-EOT foo,0 bar,1 bax,2 EOT csv = CSV.new(str, headers: ['Name', 'Count']) csv csv.headers # => ["Name", "Count"] csv.shift # => # ``` -------------------------------- ### Get default row_sep Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Retrieve the default row separator used by the CSV library. ```ruby CSV::DEFAULT_OPTIONS.fetch(:row_sep) # => :auto ``` -------------------------------- ### Initialize CSV with boolean or symbol headers Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Treats the first row of data as headers when set to true or :first_row. ```ruby str = <<-EOT Name,Count foo,0 bar,1 bax,2 EOT csv = CSV.new(str, headers: true) csv # => # csv.headers # => ["Name", "Count"] csv.shift # => # ``` -------------------------------- ### Get remaining input in CSV::Parser::InputsScanner Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV/Parser/InputsScanner.html Returns the remaining data in the scanner. ```ruby def rest @scanner.rest end ``` -------------------------------- ### Get Default Unconverted Fields Setting Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Retrieves the default value for the unconverted_fields option, which is nil. ```ruby CSV::DEFAULT_OPTIONS.fetch(:unconverted_fields) # => nil ``` -------------------------------- ### CSV Parsing - File Input Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Explains how to parse CSV data from a file using its path with `CSV.read`, `CSV.foreach`, and `CSV.table`. ```APIDOC ## CSV Parsing - File Input This section covers parsing CSV data when the input is a file. ### `CSV.read(path)` Reads the entire content of a CSV file and returns it as an Array of Arrays. **Parameters**: - `path` (String) - The file path to the CSV file. **Returns**: - Array> - An array where each inner array represents a row of CSV data. **Example**: ```ruby # Assuming 't.csv' contains: # foo,0 # bar,1 # baz,2 CSV.read('t.csv') # => [["foo", "0"], ["bar", "1"], ["baz", "2"]] ``` ### `CSV.foreach(path)` Iterates over each row of a CSV file, passing each row to a block. **Parameters**: - `path` (String) - The file path to the CSV file. - `block` - A block that accepts a row (Array) as an argument. **Example**: ```ruby CSV.foreach('t.csv') do |row| p row end # Output: # ["foo", "0"] # ["bar", "1"] # ["baz", "2"] ``` ### `CSV.table(path)` Reads the entire content of a CSV file and returns it as a `CSV::Table` object, which is useful for CSVs with headers. **Parameters**: - `path` (String) - The file path to the CSV file. **Returns**: - CSV::Table - A `CSV::Table` object representing the CSV data. **Example**: ```ruby CSV.table('t.csv') # => # ``` ``` -------------------------------- ### Get Headers - CSV::Parser Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV/Parser.html Returns the parsed headers of the CSV data. This is an internal method. ```ruby def headers @headers end ``` -------------------------------- ### Open CSV with path or file Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Creating a CSV object using either a file path or an open File object. ```ruby csv = CSV.open(path) csv # => # ``` ```ruby csv = CSV.open(File.open(path)) csv # => # ``` -------------------------------- ### CSV::InputsScanner Class Overview Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV/Parser/InputsScanner.html Provides an overview of the CSV::InputsScanner class, its purpose, and its core functionalities. ```APIDOC ## CSV::InputsScanner CSV::InputsScanner receives IO inputs, encoding and the chunk_size. It also controls the life cycle of the object with its methods `keep_start`, `keep_end`, `keep_back`, `keep_drop`. CSV::InputsScanner.scan() tries to match with pattern at the current position. If there's a match, the scanner advances the “scan pointer” and returns the matched string. Otherwise, the scanner returns nil. CSV::InputsScanner.rest() returns the “rest” of the string (i.e. everything after the scan pointer). If there is no more data (eos? = true), it returns “”. ``` -------------------------------- ### Get Default Strip Option Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Retrieves the default value for the `strip` option from `CSV::DEFAULT_OPTIONS`, which is `false`. ```ruby CSV::DEFAULT_OPTIONS.fetch(:strip) # => false ``` -------------------------------- ### GET values_at Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV/Table.html Retrieves specific rows or columns from the CSV table based on provided indices or headers. ```APIDOC ## GET values_at ### Description Retrieves data from the CSV table. If the access mode is :row or :col_or_row and arguments are Integers or Ranges, it returns rows as CSV::Row objects. Otherwise, it returns columns data as arrays. ### Method GET ### Parameters #### Query Parameters - **indices_or_headers** (Integer, Range, or String) - Required - A variable number of arguments representing row indices, ranges of indices, or column headers. ### Response #### Success Response (200) - **result** (Array) - An array of CSV::Row objects or an array of arrays containing column data. ``` -------------------------------- ### Define Converter Lists in Ruby Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Demonstrates how to create and use converter lists, which are arrays that can contain procs, names of stored converters, or nested lists. These are used for organizing multiple conversion rules. ```ruby numeric_converters = [:integer, :float] date_converters = [:date, :date_time] [numeric_converters, strip_converter] [strip_converter, date_converters, :float] ``` -------------------------------- ### Instance Method: match? Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV/MatchP.html The match? method checks if the object matches a given pattern using the =~ operator. ```APIDOC ## Instance Method: match? ### Description Checks if the current object matches the provided pattern. ### Method Instance Method ### Parameters - **pattern** (Object) - Required - The pattern to match against the object. ### Request Example ```ruby csv_match_p.match?(/pattern/) ``` ### Response - **result** (Boolean) - Returns true if the pattern matches, false otherwise. ``` -------------------------------- ### Get CSV Column Separator Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Returns the encoded column separator used for parsing and writing. Defaults to a comma. ```ruby CSV.new('').col_sep # => "," ``` ```ruby # File csv.rb, line 1821 def col_sep parser.column_separator end ``` -------------------------------- ### CSV Configuration Options Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Documentation for the row_sep and col_sep options used in CSV parsing and generation. ```APIDOC ## CSV Configuration Options ### Description This section covers the configuration options for customizing CSV data processing, specifically row and column separators. ### Parameters #### Request Body - **row_sep** (String or Symbol) - Optional - Specifies the row separator. Defaults to :auto. Can be a custom string or :auto for auto-discovery. - **col_sep** (String) - Optional - Specifies the field separator. Defaults to ",". Must be 1 or more characters for parsing. ### Notes - **row_sep**: When set to :auto, the parser attempts to detect line endings (\r\n, \n, or \r). If not found, it defaults to $INPUT_RECORD_SEPARATOR. - **col_sep**: Must be a string. Providing an empty string for parsing will raise an ArgumentError. ``` -------------------------------- ### Get Default Nil Value Option Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Retrieves the default value for the `nil_value` option from `CSV::DEFAULT_OPTIONS`, which is `nil`. ```ruby CSV::DEFAULT_OPTIONS.fetch(:nil_value) # => nil ``` -------------------------------- ### Get Default Liberal Parsing Option Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Retrieves the default value for the `liberal_parsing` option from `CSV::DEFAULT_OPTIONS`, which is `false`. ```ruby CSV::DEFAULT_OPTIONS.fetch(:liberal_parsing) # => false ``` -------------------------------- ### Get Default Quote Character Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Retrieves the default character used for quoting fields in CSV parsing and generation. ```ruby CSV::DEFAULT_OPTIONS.fetch(:quote_char) # => "\"" (double quote) ``` -------------------------------- ### Create CSV Instance with Integer Field Converter Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Initializes a CSV instance with a string and applies the :integer converter. The converter is active for subsequent reads. ```ruby string = "foo,0\nbar,1\nbaz,2\n" csv = CSV.new(string, converters: :integer) # Field converters in effect: csv.converters # => [:integer] csv.read # => [["foo", 0], ["bar", 1], ["baz", 2]] ``` -------------------------------- ### Get Default Field Size Limit Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Retrieves the default value for the field size limit, which is nil, indicating no limit. ```ruby CSV::DEFAULT_OPTIONS.fetch(:field_size_limit) # => nil ``` -------------------------------- ### Initialize CSV::FieldsConverter Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV/FieldsConverter.html Initializes the converter instance with options for nil and empty value handling. ```ruby def initialize(options={}) @converters = [] @nil_value = options[:nil_value] @empty_value = options[:empty_value] @empty_value_is_empty_string = (@empty_value == "") @accept_nil = options[:accept_nil] @builtin_converters = options[:builtin_converters] @need_static_convert = need_static_convert? end ``` -------------------------------- ### GET /table/index_or_header Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV/Table.html Retrieves rows by index/range or column values by header name, depending on the current table access mode. ```APIDOC ## GET /table/index_or_header ### Description Accesses table data. If the mode is :row or :col_or_row with an Integer/Range, it returns rows. Otherwise, it returns column values by header. ### Parameters #### Path Parameters - **index_or_header** (Integer|Range|String) - Required - The index or range for row access, or the header name for column access. ### Response #### Success Response (200) - **result** (Array|CSV::Row|nil) - The requested row(s) or column values. ``` -------------------------------- ### Initialize CSV::Parser::InputsScanner Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV/Parser/InputsScanner.html Initializes a new scanner instance with inputs, encoding, and an optional chunk size. ```ruby def initialize(inputs, encoding, chunk_size: 8192) @inputs = inputs.dup @encoding = encoding @chunk_size = chunk_size @last_scanner = @inputs.empty? @keeps = [] read_chunk end ``` -------------------------------- ### Generate CSV with CSV.generate Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Demonstrates the usage of CSV.generate to create a CSV string. Note that passing an integer will raise a TypeError. ```ruby CSV.generate(0) ``` ```ruby def generate(str=nil, **options) encoding = options[:encoding] # add a default empty String, if none was given if str str = StringIO.new(str) str.seek(0, IO::SEEK_END) str.set_encoding(encoding) if encoding else str = +"" str.force_encoding(encoding) if encoding end csv = new(str, **options) # wrap yield csv # yield for appending csv.string # return final String end ``` -------------------------------- ### Get Line Number - CSV::Parser Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV/Parser.html Returns the current line number being processed in the CSV data. This is an internal method. ```ruby def lineno @lineno end ``` -------------------------------- ### Get Current Line - CSV::Parser Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV/Parser.html Returns the content of the current line being processed. This is an internal method that delegates to `last_line`. ```ruby def line last_line end ``` -------------------------------- ### CSV generation without write_headers Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Shows how to open a CSV file for writing with headers defined, but without explicitly enabling `write_headers`. The header row will not be included in the output file. ```ruby file_path = 't.csv' CSV.open(file_path,'w', :headers => ['Name','Value'] ) do |csv| csv << ['foo', '0'] end CSV.open(file_path) do |csv| csv.shift end # => ["foo", "0"] ``` -------------------------------- ### Get Row Separator - CSV::Parser Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV/Parser.html Returns the character or string used to separate rows in the CSV data. This is an internal method. ```ruby def row_separator @row_separator end ``` -------------------------------- ### Skip blank lines in CSV Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Demonstrates how to ignore blank lines during parsing. ```ruby str = <<-EOT foo,0 bar,1 baz,2 , EOT ``` ```ruby ary = CSV.parse(str) ary # => [["foo", "0"], [], ["bar", "1"], ["baz", "2"], [], [nil, nil]] ``` ```ruby ary = CSV.parse(str, skip_blanks: true) ary # => [["foo", "0"], ["bar", "1"], ["baz", "2"], [nil, nil]] ``` ```ruby ary = CSV.parse(str, skip_blanks: :foo) ary # => [["foo", "0"], ["bar", "1"], ["baz", "2"], [nil, nil]] ``` -------------------------------- ### Get Field Size Limit - CSV::Parser Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV/Parser.html Returns the maximum allowed size for a single field in the CSV. This is an internal method. ```ruby def field_size_limit @field_size_limit end ``` -------------------------------- ### Initialize CSV::Row Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV/Row.html Constructs a new CSV::Row. Use this when creating rows manually. It handles cases where headers and fields have different sizes by padding with nil. ```ruby def initialize(headers, fields, header_row = false) @header_row = header_row headers.each { |h| h.freeze if h.is_a? String } # handle extra headers or fields @row = if headers.size >= fields.size headers.zip(fields) else fields.zip(headers).each(&:reverse!) end end ``` -------------------------------- ### Get Column Separator - CSV::Parser Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV/Parser.html Returns the configured column separator character used in the CSV data. This is an internal method. ```ruby def column_separator @column_separator end ``` -------------------------------- ### CSV Constructor Implementation Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/Object.html The source code for the CSV constructor method, which delegates to `CSV.instance`. This is the underlying implementation of the CSV object creation. ```ruby # File csv.rb, line 2653 def CSV(*args, &block) CSV.instance(*args, &block) end ``` -------------------------------- ### Generate CSV from Scratch Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Creates a new CSV string from an empty state by adding rows within a block. ```ruby output_string = CSV.generate do |csv| csv << ['foo', 0] csv << ['bar', 1] csv << ['baz', 2] end output_string # => "foo,0\nbar,1\nbaz,2\n" ``` -------------------------------- ### Open CSV with block Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Using a block with CSV.open to automatically handle the CSV object. ```ruby csv = CSV.open(path) {|csv| p csv} csv # => # ``` ```ruby # ``` -------------------------------- ### Parse CSV with Default Skip Lines Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Parses a CSV string using the default behavior where comment lines starting with '#' are included. ```ruby str = "# Comment\nfoo,0\nbar,1\nbaz,2\n# Another comment\n" ary = CSV.parse(str) ary # => [["# Comment"], ["foo", "0"], ["bar", "1"], ["baz", "2"], ["# Another comment"]] ``` -------------------------------- ### CSV::InputsScanner Public Class Methods Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV/Parser/InputsScanner.html Documentation for the public class methods of CSV::InputsScanner. ```APIDOC ### Public Class Methods new(inputs, encoding, chunk_size: 8192) click to toggle source ``` ruby # File csv/parser.rb, line 87 def initialize(inputs, encoding, chunk_size: 8192) @inputs = inputs.dup @encoding = encoding @chunk_size = chunk_size @last_scanner = @inputs.empty? @keeps = [] read_chunk end ``` ``` -------------------------------- ### Get IO Stat Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Retrieves the stat object for the underlying IO object, if supported. This provides file system information about the data source. ```ruby def stat(*args) raise NotImplementedError unless @io.respond_to?(:stat) @io.stat(*args) end ``` -------------------------------- ### Get Row Separator Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Returns the encoded string used to separate rows in the CSV data. This is used for both parsing and writing CSV files. ```ruby CSV.new('').row_sep ``` ```ruby def row_sep parser.row_separator end ``` -------------------------------- ### POST /CSV::Table/new Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV/Table.html Constructs a new CSV::Table object from an array of rows. ```APIDOC ## POST /CSV::Table/new ### Description Constructs a new CSV::Table from an array of CSV::Row objects. ### Parameters #### Request Body - **array_of_rows** (Array) - Required - An array of CSV::Row objects. - **headers** (Array) - Optional - An array of headers. If not provided, headers are fetched from the first row. ``` -------------------------------- ### CSV Parsing - String Input Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Demonstrates how to parse CSV data directly from a String object using `CSV.parse` and `CSV.parse_line`, as well as the `String#parse_csv` instance method. ```APIDOC ## CSV Parsing - String Input This section covers parsing CSV data when the input is provided as a String. ### `CSV.parse(string)` Parses the entire CSV data from a string and returns it as an Array of Arrays. **Parameters**: - `string` (String) - The CSV data to parse. **Returns**: - Array> - An array where each inner array represents a row of CSV data. **Example**: ```ruby string = "foo,0\nbar,1\nbaz,2\n" CSV.parse(string) # => [["foo", "0"], ["bar", "1"], ["baz", "2"]] ``` ### `CSV.parse_line(string)` Parses only the first line (row) of CSV data from a string. **Parameters**: - `string` (String) - The CSV data to parse. **Returns**: - Array - An array representing the first row of CSV data. **Example**: ```ruby string = "foo,0\nbar,1\nbaz,2\n" CSV.parse_line(string) # => ["foo", "0"] ``` ### `String#parse_csv` An instance method added to String that parses the first line of CSV data. **Parameters**: - None **Returns**: - Array - An array representing the first row of CSV data. **Example**: ```ruby string = "foo,0\nbar,1\nbaz,2\n" string.parse_csv # => ["foo", "0"] ``` ``` -------------------------------- ### Get Default Empty Value Option Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Retrieves the default value for the `empty_value` option from `CSV::DEFAULT_OPTIONS`, which is an empty string `""`. ```ruby CSV::DEFAULT_OPTIONS.fetch(:empty_value) # => "" ``` -------------------------------- ### CSV initialization with non-string quote_char Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Demonstrates that the quote_char option must be a string; providing a non-string value raises an ArgumentError. ```ruby # Raises ArgumentError (:quote_char has to be nil or a single character String) CSV.new('', quote_char: :foo) ``` -------------------------------- ### Get CSV headers Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html The `headers` method retrieves the headers used for parsing. It returns `nil` if no headers are defined or if the `headers` option was set to `false`. ```ruby def headers if @writer @writer.headers else parsed_headers = parser.headers return parsed_headers if parsed_headers raw_headers = @parser_options[:headers] raw_headers = nil if raw_headers == false raw_headers end end ``` -------------------------------- ### Add Multiple Converters to CSV Instance Source: https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html Shows how to sequentially add multiple field converters (:integer and :date) to a CSV instance using the `convert` method. The `converters` method then lists all active converters. ```ruby csv = CSV.new('0,1,2') csv.converters # => [] csv.convert(:integer) csv.converters # => [:integer] csv.convert(:date) csv.converters # => [:integer, :date] ```