An
if
expression in Ruby is pretty similar to ``if'' statements
in other languages.
if aSong.artist == "Gillespie" then
handle = "Dizzy"
elsif aSong.artist == "Parker" then
handle = "Bird"
else
handle = "unknown"
end
|
If you lay out your
if
statements on multiple lines, you can
leave off the
then
keyword.
if aSong.artist == "Gillespie"
handle = "Dizzy"
elsif aSong.artist == "Parker"
handle = "Bird"
else
handle = "unknown"
end
|
However, if you lay your code out more tightly, the
then
keyword
is necessary to separate the boolean expression from the following
statements.
if aSong.artist == "Gillespie" then handle = "Dizzy"
elsif aSong.artist == "Parker" then handle = "Bird"
else handle = "unknown"
end
|
You can have zero or more
elsif
clauses and an optional
else
clause.
As we've said before,
if
is
an expression, not a statement---it returns a value. You don't have
to use the value of an
if
expression, but it can come in handy.
handle = if aSong.artist == "Gillespie" then
"Dizzy"
elsif aSong.artist == "Parker" then
"Bird"
else
"unknown"
end
|
Ruby also has a negated form of the
if
statement:
unless aSong.duration > 180 then
cost = .25
else
cost = .35
end
|
Finally, for the C fans out there, Ruby also supports the C-style
conditional expression:
cost = aSong.duration > 180 ? .35 : .25
|
The conditional expression returns the value of either the expression
before or the expression after the colon, depending on whether the
boolean expression before the question mark evaluates to
true
or
false
. In this case, if the song duration is greater than 3
minutes, the expression returns .35. For shorter songs, it returns
.25. Whatever the result, it is then assigned to
cost
.