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
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: