Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Sam McCall

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

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
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS