Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby idiom: predicates and the conditional operator

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?

like image 789
pilcrow Avatar asked Jul 12 '10 18:07

pilcrow


1 Answers

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
like image 126
Jörg W Mittag Avatar answered Sep 24 '22 15:09

Jörg W Mittag