O'Reilly logo

Learn Ruby the Hard Way: A Simple and Idiomatic Introduction to the Imaginative World of Computational Thinking with Code, Third Edition by Zed A. Shaw

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required