Ruby: Read A File With One Line Of Code

Posted by luca
on Tuesday, November 27

This snippet shows how to read a file and puts all the lines into an array.

Explanation

The open method returns an IO object, that include the Enumerable module, now we can just use #map (or #collect).

The splat operator is only a sugar syntactical shortcut for map

.
Comments

Leave a response

  1. JimApril 05, 2008 @ 05:05 AM
    Beautiful snippet! Equal to paragraphs of documentation. Thanks!
  2. ErikJune 27, 2008 @ 06:14 PM
    I love this, too. Small addition if you don't want the newlines: f = *open('file.txt').map { |x| x.rstrip }
  3. StefanJuly 01, 2008 @ 01:56 AM
    Your snippet works fine, but it leaks an open file. Use this instead.
    
    f = File.readlines('file.txt').map {|l| l.rstrip}