Over a million developers have joined DZone.

Open An Arbitrary Number Of Resources Safely In Ruby

·
I'm too lazy to work out what happens if I try filenames.map {|f| File.open(f) } and the thirteenth file doesnt exist, but I bet I don't like it.

module Enumerable
  # Example:
  # ['a','b'].with_files {|f,g| ... }
  # is the same as
  # File.open('a') {|f| File.open('b') {|g| ... } }
  # You can specify modes with
  # [['a', 'rb'], ['b', 'w']].with_files ...
  def with_files(
      meth = File.method(:open),
      offset=0,
      inplace=false,
      &block
  )
    if inplace then
      if offset >= length then
        yield self
      else
        fname,mode = *self[offset]
        File.open(fname,mode) {|f| 
          self[offset] = f
          self.with_files(meth,offset+1,true,&block)
        }
      end
    else
      dup.with_files(meth,offset,true,&block)
    end
  end
end
Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}