I like judicious use of the ternary, conditional operator. To my mind it's quite succinct.
However, in ruby, I find I'm often testing predicate methods, which already have their own question marks:
some_method( x.predicate? ? foo : bar )
I'm jarred by those two question marks so close to each other. Is there an equivalently compact and readable alternative?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With