Method: CSV::Table#each

Defined in:
lib/csv/table.rb

#each(&block) ⇒ Object

:call-seq:

table.each {|row_or_column| ... ) -> self

Calls the block with each row or column; returns self.

When the access mode is :row or :col_or_row, calls the block with each CSV::Row object:

source = "Name,Value\nfoo,0\nbar,1\nbaz,2\n"
table = CSV.parse(source, headers: true)
table.by_row! # => #<CSV::Table mode:row row_count:4>
table.each {|row| p row }

Output:

#<CSV::Row "Name":"foo" "Value":"0">
#<CSV::Row "Name":"bar" "Value":"1">
#<CSV::Row "Name":"baz" "Value":"2">

When the access mode is :col, calls the block with each column as a 2-element array containing the header and an Array of column fields:

table.by_col! # => #<CSV::Table mode:col row_count:4>
table.each {|column_data| p column_data }

Output:

["Name", ["foo", "bar", "baz"]]
["Value", ["0", "1", "2"]]

Returns a new Enumerator if no block is given:

table.each # => #<Enumerator: #<CSV::Table mode:col row_count:4>:each>


930
931
932
933
934
935
936
937
938
939
940
941
942
# File 'lib/csv/table.rb', line 930

def each(&block)
  return enum_for(__method__) { @mode == :col ? headers.size : size } unless block_given?

  if @mode == :col
    headers.each.with_index do |header, i|
      yield([header, @table.map {|row| row[header, i]}])
    end
  else
    @table.each(&block)
  end

  self # for chaining
end