The reason why the conditional operator is needed in C, is because the conditional statement is, well, a statement, i.e. it doesn't (and cannot) return a value. So, if you want to return a value from conditional code, you're out of luck. That's why the conditional operator had to be added: it is an expression, i.e. it returns a value.
In Ruby, however, the conditional operator is completely superfluous because there are no statements is Ruby anyway. Everything is an expression. Specifically, there is no if
statement in Ruby, there is only an if
expression.
And since if
is an expression anyway, you can just use it instead of the cryptic conditional operator:
some_method( if x.predicate? then foo else bar end )
The only thing you have to remember is that the predicate needs to be terminated by either a newline, a semicolon or a then
. So, the first three times you do this, you will turn
if cond
foo
else
bar
end
into
if cond foo else bar end
and wonder why it doesn't work. But after that, the then
(or semicolon) will come naturally:
if cond; foo else bar end
if cond then foo else bar end