4 ms·
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 resource
by kgeist 4y ago
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?
- semiquaver 4y agoYou’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 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/1a24442193fe437e761e941d1ae0923d45fbb92f/dir.c https://github.com/ruby/ruby/blob/1a24442193fe437e761e941d1a...