From: "martinjos (Martin Sidaway)" Date: 2013-09-20T07:05:15+09:00 Subject: [ruby-core:57284] [ruby-trunk - Bug #8929] CSV.foreach(filename) without block returns failing Enumerator Issue #8929 has been updated by martinjos (Martin Sidaway). Oops - I think this isn't a bug. Sorry. I see you're meant to do CSV.open(filename) {|csv| csv.each.to_a } (otherwise you would never close the file-descriptor, I suppose...) Having said this, 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). Also, it is confusing that it currently returns an unusable Enumerator instead of letting you know that you have omitted a required parameter (namely, the block). Actually, I'm still not entirely convinced that it isn't a bug. The bug seems to be that 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. ---------------------------------------- Bug #8929: CSV.foreach(filename) without block returns failing Enumerator https://bugs.ruby-lang.org/issues/8929#change-41898 Author: martinjos (Martin Sidaway) Status: Open Priority: Normal Assignee: Category: Target version: ruby -v: 2.0.0-p247 Backport: 1.9.3: UNKNOWN, 2.0.0: UNKNOWN CSV.foreach(filename) {|entry| p entry } => works CSV.foreach(filename).to_a => fails It gives the following error: IOError: closed stream from /home/martin/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/csv.rb:1776:in `gets' from /home/martin/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/csv.rb:1776:in `block in shift' from /home/martin/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/csv.rb:1774:in `loop' from /home/martin/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/csv.rb:1774:in `shift' from /home/martin/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/csv.rb:1716:in `each' from (irb):7:in `each' from (irb):7:in `to_a' (...) -- http://bugs.ruby-lang.org/