<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: files code</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Fri, 29 Aug 2008 18:24:33 GMT</pubDate>
    <description>DZone Snippets: files code</description>
    <item>
      <title>Open an arbitrary number of resources safely in ruby</title>
      <link>http://snippets.dzone.com/posts/show/5420</link>
      <description>I'm too lazy to work out what happens if I try &lt;code&gt;filenames.map {|f| File.open(f) }&lt;/code&gt; and the thirteenth file doesnt exist, but I bet I don't like it.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;module Enumerable&lt;br /&gt;  # Example:&lt;br /&gt;  # ['a','b'].with_files {|f,g| ... }&lt;br /&gt;  # is the same as&lt;br /&gt;  # File.open('a') {|f| File.open('b') {|g| ... } }&lt;br /&gt;  # You can specify modes with&lt;br /&gt;  # [['a', 'rb'], ['b', 'w']].with_files ...&lt;br /&gt;  def with_files(&lt;br /&gt;      meth = File.method(:open),&lt;br /&gt;      offset=0,&lt;br /&gt;      inplace=false,&lt;br /&gt;      &amp;block&lt;br /&gt;  )&lt;br /&gt;    if inplace then&lt;br /&gt;      if offset &gt;= length then&lt;br /&gt;        yield self&lt;br /&gt;      else&lt;br /&gt;        fname,mode = *self[offset]&lt;br /&gt;        File.open(fname,mode) {|f| &lt;br /&gt;          self[offset] = f&lt;br /&gt;          self.with_files(meth,offset+1,true,&amp;block)&lt;br /&gt;        }&lt;br /&gt;      end&lt;br /&gt;    else&lt;br /&gt;      dup.with_files(meth,offset,true,&amp;block)&lt;br /&gt;    end&lt;br /&gt;  end&lt;br /&gt;end&lt;/code&gt;</description>
      <pubDate>Tue, 22 Apr 2008 00:44:04 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/5420</guid>
      <author>tunah (Sam McCall)</author>
    </item>
  </channel>
</rss>
