Exercise 17. More Files

Now let’s do a few more things with files. We’ll write a Ruby script to copy one file to another. It’ll be very short, but will give you ideas about other things you can do with files.

ex17.rb

 1    from_file, to_file = ARGV  2  3    puts "Copying from #{from_file} to #{to_file}"  4  5    # we could do these two on one line, how?  6    in_file = open(from_file)  7    indata = in_file.read  8  9    puts "The input file is #{indata.length} bytes long" 10 11    puts "Does the output file exist? #{File.exist?(to_file)}" 12    puts "Ready, hit RETURN to continue, CTRL-C to abort." 13    $stdin.gets 14 15    out_file = open(to_file, 'w') 16    out_file.write(indata) 17 18    puts "Alright, all ...

Get Learn Ruby the Hard Way: A Simple and Idiomatic Introduction to the Imaginative World of Computational Thinking with Code, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.