Simple Ruby Syntax

Ruby is not as widely as used a language as I would like. Here's enough of its syntax to help you read the code in my article.

March 2003



Ruby is an object-oriented language with classes and methods. Classes are introduced with the keyword class and methods with the keyword def. All blocks are ended with end. Instance variables in a class are named with a leading @, global variables have a leading $. You can declare instance variables, together with accessor functions with attr_accessor. The method initialize is called when an object is created.

One of Ruby's nicest elements are blocks. A good example of a block is looping through a collection. There's two equivalent syntaxes for printing each order in a collection of orders

orders.each {|o| print o}

and

orders.each do |o|
  print o
end

Blocks are also good for releasing resources automatically. Consider

  $dbh.select_all(“select * from FOO”) do |row|
    print row
  end

The execute method creates the necessary statement and result set objects and ensures they are closed automatically at the end of the block. Using blocks like this is awkward or impossible in Java and C# and is something old Smalltalkers miss a lot. ($dbh is the the database handle - the abbreviation is idiomatic with the dbi package)

Ruby's array is a dynamic list. You create a literal one with [foo, bar] and an empty one with [] You add elements to an array with <<.

Ruby also has hashes (aka associative arrays, dictionaries, hashmaps). You create an empty one with {} and access elements with aHash[aKey].

Ruby allows “here documents” to create multi-line strings. You start such a text block with sql = <<-END_SQL. Everything following up END_SQL is part of the string. You can insert dynamic expressions into any string with #{anOrder.price}.

For more on Ruby, I strongly recommend the pick axe book by Andy Hunt and Dave Thomas. It's available on-line if you're a skinflint. Ruby's home page is here


Significant Revisions

March 2003: