Skip to content

End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

class method

CSV.foreach

foreach(path_or_io, mode='r', **options) {|row| ... )
foreach(path_or_io, mode='r', **options) → new_enumerator

Calls the block with each row read from source path_or_io.

Path input without headers:

Example
string = "foo,0\nbar,1\nbaz,2\n"
in_path = 't.csv'
File.write(in_path, string)
CSV.foreach(in_path) {|row| p row }

Output:

Example
["foo", "0"]
["bar", "1"]
["baz", "2"]

Path input with headers:

Example
string = "Name,Value\nfoo,0\nbar,1\nbaz,2\n"
in_path = 't.csv'
File.write(in_path, string)
CSV.foreach(in_path, headers: true) {|row| p row }

Output:

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

IO stream input without headers:

Example
string = "foo,0\nbar,1\nbaz,2\n"
path = 't.csv'
File.write(path, string)
File.open('t.csv') do |in_io|
  CSV.foreach(in_io) {|row| p row }
end

Output:

Example
["foo", "0"]
["bar", "1"]
["baz", "2"]

IO stream input with headers:

Example
string = "Name,Value\nfoo,0\nbar,1\nbaz,2\n"
path = 't.csv'
File.write(path, string)
File.open('t.csv') do |in_io|
  CSV.foreach(in_io, headers: true) {|row| p row }
end

Output:

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

With no block given, returns an Enumerator:

Example
string = "foo,0\nbar,1\nbaz,2\n"
path = 't.csv'
File.write(path, string)
CSV.foreach(path) # => #<Enumerator: CSV:foreach("t.csv", "r")>

Arguments:

  • Argument path_or_io must be a file path or an IO stream.

  • Argument mode, if given, must be a File mode See Open Mode.

  • Arguments **options must be keyword options. See Options for Parsing.

  • This method optionally accepts an additional :encoding option that you can use to specify the Encoding of the data read from path or io. You must provide this unless your data is in the encoding given by Encoding::default_external. Parsing will use this to determine how to parse the data. You may provide a second Encoding to have the data transcoded as it is read. For example,

    encoding: 'UTF-32BE:UTF-8'

    would read UTF-32BE data from the file but transcode it to UTF-8 before parsing.

See also .filter .generate .generate_line also in 3.3 · 3.1 · 3.0