End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
CSV.foreach
# File tmp/rubies/ruby-3.2.0/lib/csv.rb, line 1331
def foreach(path, mode="r", **options, &block)
return to_enum(__method__, path, mode, **options) unless block_given?
open(path, mode, **options) do |csv|
csv.each(&block)
end
end
Calls the block with each row read from source path_or_io.
Path input without headers:
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:
["foo", "0"] ["bar", "1"] ["baz", "2"]
Path input with headers:
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:
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:
["foo", "0"] ["bar", "1"] ["baz", "2"]
IO stream input with headers:
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:
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_iomust be a file path or an IO stream. -
Argument
mode, if given, must be a File mode See Open Mode. -
Arguments
**optionsmust be keyword options. See Options for Parsing. -
This method optionally accepts an additional
:encodingoption that you can use to specify theEncodingof the data read frompathorio. You must provide this unless your data is in the encoding given byEncoding::default_external. Parsing will use this to determine how to parse the data. You may provide a secondEncodingto have the data transcoded as it is read. For example,encoding: 'UTF-32BE:UTF-8'
would read
UTF-32BEdata from the file but transcode it toUTF-8before parsing.