Ruby Programming
Previous Page Home Next Page

Operator Expressions

Ruby has the basic set of operators (+, -, *, /, and so on) as well as a few surprises. A complete list of the operators, and their precedences, is given in Table 18.4 on page 219.

In Ruby, many operators are actually method calls. When you write a*b+c you're actually asking the object referenced by a to execute the method ``*'', passing in the parameter b. You then ask the object that results from that calculation to execute ``+'', passing c as a parameter. This is exactly equivalent to writing


Because everything is an object, and because you can redefine instance methods, you can always redefine basic arithmetic if you don't like the answers you're getting.

class Fixnum
  alias oldPlus +
  def +(other)
1 + 2 4
a = 3
a += 4 8

More useful is the fact that classes that you write can participate in operator expressions just as if they were built-in objects. For example, we might want to be able to extract a number of seconds of music from the middle of a song. We could using the indexing operator ``[]'' to specify the music to be extracted.

class Song
  def [](fromTime, toTime)
    result = + " [extract]",
                      toTime - fromTime)

This code fragment extends class Song with the method ``[]'', which takes two parameters (a start time and an end time). It returns a new song, with the music clipped to the given interval. We could then play the introduction to a song with code such as:

aSong[0, 0.15].play
Ruby Programming
Previous Page Home Next Page

Published under the terms of the Open Publication License Design by Interspire  

© Copyright 2019