Expressions
So far we've been fairly cavalier in our use of expressions in Ruby.
After all,
a=b+c
is pretty standard
stuff. You could write a whole heap of Ruby code without reading any
of this chapter.
But it wouldn't be as much fun
;-)
.
One of the first differences with Ruby is that anything that can
reasonably return a value does: just about everything is an
expression. What does this mean in practice?
Some obvious things include the ability to chain statements together.
a = b = c = 0
|
� |
0
|
[ 3, 1, 7, 0 ].sort.reverse
|
� |
[7, 3, 1, 0]
|
Perhaps less obvious, things that are normally statements in C
or Java are expressions in Ruby. For example, the
if
and
case
statements both return the value of the last expression
executed.
songType = if song.mp3Type == MP3::Jazz
if song.written < Date.new(1935, 1, 1)
Song::TradJazz
else
Song::Jazz
end
else
Song::Other
end
rating = case votesCast
when 0...10 then Rating::SkipThisOne
when 10...50 then Rating::CouldDoBetter
else Rating::Rave
end
|
We'll talk more about
if
and
case
starting
on page 79.