Ruby idiom: predicates and conditional operator

I like the wise use of the ternary, conditional statement. In my opinion, this is pretty concise.

However, in ruby, I find that I often test predicate methods that already have their own question marks:

some_method( x.predicate? ? foo : bar ) 

I doubt these two question marks so close to each other. Is there an equivalent compact and readable alternative?

+4
source share
4 answers

The closest compressed expression you can get is

 x.predicate? && foo || bar 

which acts like a ternary operator, but more mysterious and ugly.

Is this just a case of syntactic diabetes caused by sugar by query? methods query? . I think we just need to learn how to live with him.

+8
source

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 
+11
source

Just remove the space.

 some_method( x.predicate?? foo : bar ) 

Acts equally in Ruby. Give it a try!

+3
source

I can’t say that this is simpler, but in many cases it would be useful to simply insert the predicate in brackets, for example:

 some_method((x.predicate?) ? foo : bar ) 

Does this help, especially when your predicate is not as simple as method?

+1
source

Source: https://habr.com/ru/post/1315445/


All Articles