Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a better way to check for a nil object before calling a method on it?

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?

like image 648
Ethan Avatar asked Jun 27 '09 06:06

Ethan


People also ask

How do you check if something is 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).

How do you handle nil in Ruby?

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.

What happens when you invoke a method on a nil pointer Objective-C?

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.

Why does Ruby use nil?

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.


2 Answers

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
like image 75
Joel Meador Avatar answered Sep 28 '22 07:09

Joel Meador


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.

like image 20
Jonathan Lonowski Avatar answered Sep 28 '22 05:09

Jonathan Lonowski