Cover by Michael Fitzgerald

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

Opening an Existing File

You open an existing file with the open method. Example 8-1 opens the file sonnet_129.txt (it comes with the code archive), prints each line of the file using each with a block, then closes it with close. (By the way, you can use file.closed? to test whether a file is closed. It returns true or false.)

Example 8-1. open.rb

file = File.open( "sonnet_129.txt" )

file.each { |line| print "#{file.lineno}. ", line }

file.close

The expression substitution syntax, that is, #{file.lineno}, inserts the line number in the output, followed by the line from the file.

Tip

The open, each, and close methods are all from the IO class, not File. See "The IO Class," later in this chapter.

The output is:

1. The expense of spirit in a waste of shame
2. Is lust in action: and till action, lust
3. Is perjured, murderous, bloody, full of blame,
4. Savage, extreme, rude, cruel, not to trust;
5. Enjoyed no sooner but despised straight;
6. Past reason hunted; and no sooner had,
7. Past reason hated, as a swallowed bait,
8. On purpose laid to make the taker mad.
9. Mad in pursuit and in possession so;
10. Had, having, and in quest to have extreme;
11. A bliss in proof, and proved, a very woe;
12. Before, a joy proposed; behind a dream.
13. All this the world well knows; yet none knows well
14. To shun the heaven that leads men to this hell.

I used the print method in open.rb because the line-end character already exists at the end of each line in the file.

ARGV and ARGF

Another interesting way ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required