Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace ternary nil check with ruby best practices

i find myself doing this quite a lot to protect against nil when the return of some_method returns nil.

a = a.some_method.present? ? a.some_method : []

is there a more ruby way to do it? I've tried using

a = []
a ||= a.some_method

but ofcourse that will just give me

a = []

thanks!

like image 503
user1337902 Avatar asked Aug 02 '16 01:08

user1337902


People also ask

How do you check nil in Ruby?

In Ruby, you can check if an object is nil, just by calling the nil? on the object... even if the object is nil. That's quite logical if you think about it :) Side note : in Ruby, by convention, every method that ends with a question mark is designed to return a boolean (true or false).

Does Ruby support ternary operator?

The ternary operator is a common Ruby idiom that makes a quick if/else statement easy and keeps it all on one line.

What is '?' In Ruby?

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

How does the ternary operator work in Ruby?

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. The operator first evaluates for a true or false value and then, depending upon the result of the evaluation, executes one of the two given statements​.


1 Answers

The usual pattern is:

result = method(args) || default_value

The || operator is short-circuiting. If the left-hand-side is true, it will not bother to evaluate the right hand side. In Ruby, nil is considered false. Hence if nil is returned (or false), the || evaluates the right-hand-side and returns that as the result.

Note the order of the left and right sides is important.

like image 99
Daniel Stevens Avatar answered Sep 19 '22 09:09

Daniel Stevens