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!
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).
The ternary operator is a common Ruby idiom that makes a quick if/else statement easy and keeps it all on one line.
i know that the '?' in ruby is something that checks the yes/no fulfillment.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With