[ next ] [ prev ] [ contents ] [ up to First Example ] Invitation To Ruby

Improving Our Example

Lets rewrite our example to use a function.

countlines2.rb

  1: #!/usr/bin/env ruby
  2: 
  3: def filelines(file)
  4:   count = 0
  5:   while line = file.gets
  6:     if line =~ /Ruby/
  7:       count += 1
  8:     end
  9:   end
 10:   count
 11: end
 12: 
 13: if __FILE__ == $0 then
 14:   puts "#{filelines($stdin)} lines"
 15: end

  • [3] Functions are defined using the def keyword and are terminated by a matching end.
    • The filelines function takes a single arguement named file.
  • Inside the function, we use file.gets to read lines.
    • file refers to an Object (a File object to be specific).
    • Sending a gets message to a file object returns the next line of the file.
  • [4] count is a local variable to the filelines function. It cannot be referenced outside the function.
    • Global variables start with $ and can be referenced anywhere in the program. ($stdin is the global reference to the standard input object)
  • [10] The last value evaluated in a function is automatically returned as the value of that function. You can explicitly say "return count" as well.
  • [13] The strange if test at the bottom is a magic incantation that allows our ruby code to be used as a main program or a library.


[ next ] [ prev ] [ contents ] [ up to First Example ] Copyright 2002 by Jim Weirich.
All rights reserved.