Difference between revisions of "Ruby:Read a Text File"

From Progzoo
Jump to: navigation, search
(Use readlines)
Line 23: Line 23:
  
 
==Use readlines==
 
==Use readlines==
<question lang="rb" className="Demo" copyFile="haggis.txt">You can open a text file and use the readlines method.<prog>
+
<question lang="rb" className="Demo" copyFile="haggis.txt">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).
 +
<prog>
 
f = File.open('haggis.txt')
 
f = File.open('haggis.txt')
 
a = f.readlines
 
a = f.readlines

Revision as of 18:35, 11 December 2008

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]