Ruby:Read a Text File
Jump to navigation
Jump to search
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]
or
[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]