Ruby:Read a Text File

From Progzoo
Revision as of 18:35, 11 December 2008 by Cs66 (Talk | contribs) (Use readlines)

Jump to: navigation, search

Use each_line

You can open a text file and read each line.

Note that the end of line character is included. The chomp method removes this character (on windows this is two characters).

The text file http://progzoo.net/haggis.txt includes some lines of text.

[Font] [Default] [Show] [Resize] [History] [Profile]

Use gets

You can open a text file and use the gets method.
[Font] [Default] [Show] [Resize] [History] [Profile]

Use readlines

You can open a text file and use the readlines method.

In this example all lines are read into array a. We print out line number 2 (the third line).


[Font] [Default] [Show] [Resize] [History] [Profile]