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
   1  filenames.map {|f| File.open(f) }
and the thirteenth file doesnt exist, but I bet I don't like it.

   1  module Enumerable
   2    # Example:
   3    # ['a','b'].with_files {|f,g| ... }
   4    # is the same as
   5    # File.open('a') {|f| File.open('b') {|g| ... } }
   6    # You can specify modes with
   7    # [['a', 'rb'], ['b', 'w']].with_files ...
   8    def with_files(
   9        meth = File.method(:open),
  10        offset=0,
  11        inplace=false,
  12        &block
  13    )
  14      if inplace then
  15        if offset >= length then
  16          yield self
  17        else
  18          fname,mode = *self[offset]
  19          File.open(fname,mode) {|f| 
  20            self[offset] = f
  21            self.with_files(meth,offset+1,true,&block)
  22          }
  23        end
  24      else
  25        dup.with_files(meth,offset,true,&block)
  26      end
  27    end
  28  end
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS