ruby on rails - Why does Object::try work if it's sent to a nil object? -
if try call method on nil object in ruby, nomethoderror exception arises message:
"undefined method ‘...’ nil:nilclass" however, there try method in rails return nil if it's sent nil object:
require 'rubygems' require 'active_support/all' nil.try(:nonexisting_method) # no nomethoderror exception anymore so how try work internally in order prevent exception?
activesupport 4.0.0 defines 2 try methods: one object instances:
class object def try(*a, &b) if a.empty? && block_given? yield self else public_send(*a, &b) if respond_to?(a.first) end end end the other nilclass instances (nil objects):
class nilclass def try(*args) nil end end now, suppose have object instance (excluding nil, inherits object, else in ruby), defining method returns nil:
class test def returns_nil nil end end so, running test.new.try(:returns_nil) or test.new.not_existing_method, object#try called, check if public method exists (the respond_to?); if call method (the public_send), else return nil (there aren't other lines).
if call try on of these returning nil methods:
test.new.try(:returns_nil).try(:any_other_method) test.new.try(:not_existing_method).try(:any_other_method) we call nilclass#try, nil#try, ignores , returns nil. other try called on nil instance , return nil.
Comments
Post a Comment