Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I'm not familiar with Ruby, so I have a question: the first snippet has the .close method called while the second doesn't. Does the second example leak resources, or it's automatically closed after a GC in a finalizer, maybe? Does .each close the directory? Or, maybe, .close is a no-op in newer versions?


You’re quite right. OP’s rewrite contains a bug: it leaks one file descriptor per invocation. The correct version passes a block to `open` directly so that it’s automatically closed when the block is done executing. Maybe golfing down to be “idiomatic” isn’t always best :)

  Dir.open('.') do |dirp|
    dirp.each do |f|
      puts f if f.match?(/\.rb\z/)
    end
  end

https://ruby-doc.org/core-3.1.0/Dir.html#method-c-open

There are a few ruby stdlib classes like Tempfile that use the finalizer trick you mention to free resources on GC but Dir isn’t one of them. Here’s it’s implementation:

https://github.com/ruby/ruby/blob/1a24442193fe437e761e941d1a...




Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: