Exercise 20. Functions and Files

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) 24 25    puts "Let's print three lines:" 26 27    current_line = 1 28    print_a_line(current_line, ...

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.