<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="/stylesheets/rss.css" type="text/css"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">
  <channel>
    <title>loopkid: read file with one line of code</title>
    <link>http://loopkid.net/articles/2008/07/01/read-file-with-one-line-of-code</link>
    <language>en-us</language>
    <ttl>40</ttl>
    <description>professional procrastinator</description>
    <item>
      <title>read file with one line of code</title>
      <description>&lt;p&gt;There are probably at least a have a dozen ways to print the contents of a file in Ruby, here I will present four ways of doing it.&lt;/p&gt;

&lt;p&gt;The first method is rather verbose. Assign a file object and iterate on the file object with the &lt;code&gt;each_line&lt;/code&gt; method and then close the file.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;f = open('file.txt')
f.each_line do |line|
  puts line
end
f.close
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The second method still assigns a file object, but then uses the more compact &lt;code&gt;readlines&lt;/code&gt; instance method and closes the file.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;f = open('file.txt')
puts f.readlines
f.close
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The third method uses block form to access the file and automatically close it.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;open('file.txt') { |f| puts f.readlines }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The fourth method calls the class method &lt;code&gt;readlines&lt;/code&gt; to wrap it all up in one statement.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;puts File.readlines('file.txt')
&lt;/code&gt;&lt;/pre&gt;</description>
      <pubDate>Tue, 01 Jul 2008 01:58:00 +0200</pubDate>
      <guid isPermaLink="false">urn:uuid:760b092c-1d98-4618-b7fa-cea31ac3ff8f</guid>
      <author>Stefan</author>
      <link>http://loopkid.net/articles/2008/07/01/read-file-with-one-line-of-code</link>
      <category>English</category>
      <category>Ruby</category>
      <trackback:ping>http://loopkid.net/articles/trackback/8471</trackback:ping>
    </item>
  </channel>
</rss>

