[ next ] [ prev ] [ contents ] [ skip to So ... What is Ruby? ] Invitation To Ruby

First Example

Lets jump right into some example code.

Problem: Count the number of lines in a file that contain the word "Ruby".

countlines.rb

  1: #!/usr/bin/env ruby
  2: 
  3: count = 0
  4: while line = gets
  5:   if line =~ /Ruby/
  6:     count += 1
  7:   end
  8: end
  9: puts "#{count} Ruby lines"

  • [1] The "#!" is the standard way to run scripts
  • [3] count is a variable. It springs into existance the moment we give a a value (e.g. 0).
  • [4-8] The while line is the start of a loop. As long as the while condiditon is true, the body of the loop (through the matching end) will execute over and over again.
    • The condition of the while is an assignment expression that reads one line from standard input (using gets) and assignes it to the variable line.
  • [5] Ruby has regular expressions, very similar to those in Perl. This expression is true if the line contains the word Ruby.
  • [6] count is incremented by one whenever the condition is true.
  • [9] The puts function writes a string to standard output.
    • Ruby executes the code in the #{...} construct in the string and replaces the #{...} with the value of the executed code.
    • This is similar to interpolated string in Perl, except that it is not limited to variable values (any legal Ruby code is allowed).

See also: Perl Version


[ next ] [ prev ] [ contents ] [ skip to So ... What is Ruby? ] Copyright 2002 by Jim Weirich.
All rights reserved.