Method: CSV#each
- Defined in:
- lib/csv.rb
#each(&block) ⇒ Object
:call-seq:
csv.each -> enumerator
csv.each {|row| ...}
Calls the block with each successive row. The data source must be opened for reading.
Without headers:
string = "foo,0\nbar,1\nbaz,2\n"
csv = CSV.new(string)
csv.each do |row|
p row
end
Output:
["foo", "0"]
["bar", "1"]
["baz", "2"]
With headers:
string = "Name,Value\nfoo,0\nbar,1\nbaz,2\n"
csv = CSV.new(string, headers: true)
csv.each do |row|
p row
end
Output:
<CSV::Row "Name":"foo" "Value":"0">
<CSV::Row "Name":"bar" "Value":"1">
<CSV::Row "Name":"baz" "Value":"2">
Raises an exception if the source is not opened for reading:
string = "foo,0\nbar,1\nbaz,2\n"
csv = CSV.new(string)
csv.close
# Raises IOError (not opened for reading)
csv.each do |row|
p row
end
2554 2555 2556 2557 2558 2559 2560 2561 2562 |
# File 'lib/csv.rb', line 2554 def each(&block) return to_enum(__method__) unless block_given? begin while true yield(parser_enumerator.next) end rescue StopIteration end end |