I can see that it is tricky, because a normal enumerator created by calling CSV#each shouldn't necessarily close the file (as the user may want to call #rewind), but when you use CSV.foreach you have no reference to the CSV object, and you don't want the file handle to be left open.
However, I don't see why, in principle, CSV.foreach(filename) as an Enumerator shouldn't be supported. It has clear, well-defined semantics: it just has to close the file automatically after yielding the last entry.
Also, this would be consistent with, amongst other things, File.foreach(filename).
The present behaviour occurs because self.foreach() uses the block form of self.open(), which ensures the csv object is closed after yielding it. It then calls csv.each(&block) inside the open block, which is okay if a block was passed in to self.foreach, but if not, the no-block form of each() simply calls to_enum (from Object). This enumerator then gets passed out of the open block (becoming invalidated in the process), and out of self.foreach.
In other words:
class CSV
def self.foreach(path, options = Hash.new, &block)
open(path, options) do |csv|
csv.each(&block)
end
end
def self.open(*args)
(...)
if block_given?
begin
yield csv
ensure
csv.close
end
else
csv
end
end
def each
if block_given?
while row = shift
yield row
end
else
to_enum
end
end
end
A solution might be to create an alternative version of CSV#each that calls CSV#close after the last entry:
def each_closing
if block_given?
begin
while row = shift
yield row
end
ensure
close
end
else
to_enum(method) # method returns :each_closing
end
end
Then CSV.foreach could be:
def self.foreach(path, options = Hash.new, &block)
open(path, options).each_closing(&block)
end