Exercise 20. Functions and Files

Image

Remember your checklist for functions, then do this exercise paying close attention to how functions and files can work together to make useful stuff.

ex20.rb

 1    input_file = ARGV.first  2  3    def print_all(f)  4      puts f.read  5    end  6  7    def rewind(f)  8      f.seek(0)  9    end 10 11    def print_a_line(line_count, f) 12      puts "#{line_count}, #{f.gets.chomp}" 13    end 14 15    current_file = open(input_file) 16 17    puts "First let's print the whole file:\n" 18 19    print_all(current_file) 20 21    puts "Now let's rewind, kind of like a tape." 22 23    rewind(current_file) ...

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

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.