Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby ternary operator without else

Is there a ruby idiom for "If do-this," and "do-this" just as a simple command?

for example, I'm currently doing

object.method ? a.action : nil 

to leave the else clause empty, but I feel like there's probably a more idiomatic way of doing this that doesn't involve having to specify a nil at the end. (and alternatively, I feel like taking up multiple lines of code would be wasteful in this case.

like image 475
RyanCacophony Avatar asked Feb 01 '10 03:02

RyanCacophony


People also ask

Does Ruby have ternary operator?

The conditional ternary operator assigns a value to a variable based on some condition. This operator is used in place of the if-else statement.

How does the ternary operator work in Ruby?

The ternary operator is used to return a value based on the result of a binary condition. It takes in a binary condition as input, which makes it similar to an 'if-else' control flow block. It also, however, returns a value, behaving similar to a function.

What is '?' In Ruby?

i know that the '?' in ruby is something that checks the yes/no fulfillment.


1 Answers

As a general rule: you pretty much never need the ternary operator in Ruby. The reason why you need it in C, is because in C if is a statement, so if you want to return a value you have to use the ternary operator, which is an expression.

In Ruby, everything is an expression, there are no statements, which makes the ternary operator pretty much superfluous. You can always replace

cond ? then_branch : else_branch 

with

if cond then then_branch else else_branch end 

So, in your example:

object.method ? a.action : nil 

is equivalent to

if object.method then a.action end 

which as @Greg Campbell points out is in turn equivalent to the trailing if modifier form

a.action if object.method 

Also, since the boolean operators in Ruby not just return true or false, but the value of the last evaluated expression, you can use them for control flow. This is an idiom imported from Perl, and would look like this:

object.method and a.action 
like image 176
Jörg W Mittag Avatar answered Oct 14 '22 10:10

Jörg W Mittag