views:

63

answers:

2

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?

+6  A: 

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
Jörg W Mittag
I upvoted, but really? Cryptic? I don't think any programmer would find the conditional operator cryptic, and personally I would rather see that than "if conditon foo else bar end" in a method call.
Ed Swangren
+1 for the `then`/`;` remark and discussion of the operator.
pilcrow
+4  A: 

The closest succinct expression you can get is

x.predicate? && foo || bar

which acts sort of a ternary operator, but more cryptic and ugly.

It's just a case of syntactic diabetes caused by the sugar on the query? methods. I guess we'll just have to learn to live with it.

Chubas
+1 for crypticness++ and ugliness++.
pilcrow