MC logo

File I/O

  Ruby Example Code

<<Basic I/O II io4.rb Parallel Asst.>>
# Get the parts of speech.
print "Please enter a past-tense verb: "
verb = gets.chomp
print "Please enter a noun: "
noun = gets.chomp
print "Please enter a proper noun: "
prop_noun = gets.chomp
print "Please enter a an adverb: "
adv = gets.chomp

# See where to put it.
print "Please enter a file name: "
fn = gets.chomp
handle = open(fn,"w")

# Go.
printf(handle, "%s got a %s and\n%s %s around the block.\n",
        prop_noun, noun, verb, adv)

See:Ruby Manual [1][2]

This version opens a file for writing, and writes its output to a file selected by the user. The second argument to open is the same as the second argument to a plain C fopen, except it will default to reading.

The object returned from open is class File.
<<Basic I/O II Parallel Asst.>>