Andrew
Andrew

Reputation: 238667

How to safely retrieve the value of a Ruby method that might not exist?

I thought I understood how try works, but I'm getting an undefined method error:

unknown_object.try(:some_method).try(:get_value)

I found in the documentation for try that it only rescues from an undefined method error if the object is nil. In my case, I know my object is not nil, but I'm not sure if it has the method I need.

How can I safely retrieve (and chain) the methods together so that I don't get undefined method errors?

Upvotes: 1

Views: 708

Answers (2)

Stefan
Stefan

Reputation: 114138

The behavior you're looking for was implemented in Rails 4:

Object#try will now return nil instead of raise a NoMethodError if the receiving object does not implement the method, but you can still get the old behavior by using the new Object#try!.

Here's the Rails 4 source code for the new try:

def try(*a, &b)
  if a.empty? && block_given?
    yield self
  else
    public_send(*a, &b) if respond_to?(a.first)
  end
end

The only difference is if respond_to?(a.first).

Upvotes: 3

usha
usha

Reputation: 29349

try works as expected only when you call it on nil object. Since your's is a valid object, I think what you need is respond to

if unknown_object.respond_to?(:some_method)
  unknown_object.some_method.get_value
end

Upvotes: 3

Related Questions