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)
|
oldPlus(other).succ
|
end
|
end
|
|
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 = Song.new(self.title + " [extract]",
self.artist,
toTime - fromTime)
result.setStartTime(fromTime)
result
end
end
|
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: