I have this method call I have to use...
financial_document.assets.length
But financial_document.assets
could be nil
.
I could use...
financial_document.assets.nil? ? '0' : financial_document.assets.length
Is there a less repetitive way to do that?
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).
However, in terms of how it's implemented, nil is fundamentally different than in other languages. In Ruby, nil is—you've guessed it—an object. It's the single instance of the NilClass class. Since nil in Ruby is just an object like virtually anything else, this means that handling it is not a special case.
You can validly send any message to a "nil" pointer in Objective-C. This is very different to languages like C++ where invoking a method on a "NULL" pointer will likely crash your program. Sending a message to "nil" will have only one effect: it will return a zero value. No other action will occur.
Well, nil is a special Ruby object used to represent an “empty” or “default” value. It's also a “falsy” value, meaning that it behaves like false when used in a conditional statement.
Dave W. Smith is on the right track.
Check this out: http://www.nach-vorne.de/2007/4/24/attr_accessor-on-steroids
One easy solution would look something like this:
class FinancialDocument
attr_accessor :assets
def assets
@assets ||= Array.new
end
...
end
Personally, I would use the or
operator/keyword:
(financial_document.assets or []).length
Either way, .length
is called on an array, giving you 0
if nil
.
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