class CSV::Row

CSV::Row

A CSV::Row instance represents a CSV table row. (see class CSV).

The instance may have: * Fields: each is an object, not necessarily a String. * Headers: each serves a key, and also need not be a String.

Instance Methods

CSV::Row has three groups of instance methods: * Its own internally defined instance methods. * Methods included by module Enumerable. * Methods delegated to class Array.: * Array#empty? * Array#length * Array#size

Creating a CSV::Row Instance

Commonly, a new CSV::Row instance is created by parsing CSV source that has headers: source = “Name,Value\nfoo,0\nbar,1\nbaz,2\n” table = CSV.parse(source, headers: true) table.each {|row| p row }

Output: #<CSV::Row “Name”:“foo” “Value”:“0”> #<CSV::Row “Name”:“bar” “Value”:“1”> #<CSV::Row “Name”:“baz” “Value”:“2”>

You can also create a row directly. See ::new.

Headers

Like a CSV::Table, a CSV::Row has headers.

A CSV::Row that was created by parsing CSV source inherits its headers from the table: source = “Name,Value\nfoo,0\nbar,1\nbaz,2\n” table = CSV.parse(source, headers: true) row = table.first row.headers # => [“Name”, “Value”]

You can also create a new row with headers; like the keys in a Hash, the headers need not be Strings: row = CSV::Row.new([:name, :value], [‘foo’, 0]) row.headers # => [:name, :value]

The new row retains its headers even if added to a table that has headers: table << row # => #<CSV::Table mode:col_or_row row_count:5> row.headers # => [:name, :value] row # => “foo” row # => nil

Accessing Fields

You may access a field in a CSV::Row with either its Integer index (Array-style) or its header (Hash-style).

Fetch a field using method []: row = CSV::Row.new([‘Name’, ‘Value’], [‘foo’, 0]) row # => 0 row # => 0

Set a field using method []=: row = CSV::Row.new([‘Name’, ‘Value’], [‘foo’, 0]) row # => #<CSV::Row “Name”:“foo” “Value”:0> row = ‘bar’ row = 1 row # => #<CSV::Row “Name”:“bar” “Value”:1>