Explanation for ruby's CSV.foreach enumerator?

1.3k views Asked by At

Ruby's CSV.foreach('file.csv', headers: true) returns an enumerator, but I can't seem to call any enumerable methods on it, i.e. I can't call CSV.foreach('file.csv', headers: true).map(&:to_hash) or even CSV.foreach('file.csv', headers: true).to_a. This is unexpected behavior, as I can call these methods on other enumerators like 1.upto(5).to_a etc. What's the explanation for this?

1

There are 1 answers

3
Alex.Bullard On BEST ANSWER

Take a look at the source here. At the time of writing, CSV::foreach is defined as

def self.foreach(path, options = Hash.new, &block)
  open(path, options) do |csv|
    csv.each(&block)
  end
end

so the each enumerator is enclosed within the open block and the method returns nil. If you want to interact w/ the enumerator you can do something like

CSV.open('file.csv') do |csv|
  csv.each.map do |row|
    # whatever
  end
end