The reason the conditional operator is needed in C is because the conditional operator is, well, an operator, that is, it does not return (and cannot) the value. So, if you want to return a value from a conditional code, you're out of luck. To do this, you had to add a conditional operator: this is an expression, that is, it returns a value.
In Ruby, however, the conditional operator is completely redundant, since there are no instructions in Ruby. All this expression. In particular, in Ruby there is no if , only an if exists.
And since if is an expression anyway, you can simply use it instead of the cryptic conditional statement:
some_method( if x.predicate? then foo else bar end )
The only thing you should remember is that the predicate must be interrupted by either a new line, a semicolon, or then . So, the first three times you do it, you turn
if cond foo else bar end
in
if cond foo else bar end
and wonder why this is not working. But after that, then (or semicolon) will come naturally:
if cond; foo else bar end if cond then foo else bar end
source share