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

From Progzoo
Jump to: navigation, search
(Use readlines)
(Use each_line)
Line 3: Line 3:
 
<question lang="rb" className="Demo" copyFile="haggis.txt">You can open a text file and read each line.<prog>
 
<question lang="rb" className="Demo" copyFile="haggis.txt">You can open a text file and read each line.<prog>
 
File.open('haggis.txt').each_line{ |s|
 
File.open('haggis.txt').each_line{ |s|
  s = s.chomp
 
 
   puts s
 
   puts s
 
}
 
}
 
</prog>
 
</prog>
Note that the end of line character is included. The chomp method
+
This code iterates over each line of the file.
removes this character (on windows this is two characters).
+
 
<p>
 
<p>
 
The text file http://progzoo.net/haggis.txt includes some lines of text.
 
The text file http://progzoo.net/haggis.txt includes some lines of text.

Revision as of 18:39, 11 December 2008

Use each_line

You can open a text file and read each line.

This code iterates over each line of the file.

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]