Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
# in ruby, nil is an instance of NilClass. we're monkeypatching NilClass at this point, which is a bad idea for a production app.
# but for this example, it gets the point across and should help you find a solution to what you want... maybe...
class NilClass
def method_missing(name, *args)
if respond_to? name
return name(*args)
else
puts "do something about #{name} being nil, here"
# this will forward the call to the original NilClass.method_missing
# which will raise the standard "undefined method ..." exception
# commented out for now, to show you can prevent the error
# super name, *args
end
end
end
class X
attr_accessor :y
end
class Y
attr_accessor :z
end
class Z
attr_accessor :foo
end
require 'ostruct'
somex = X.new
somex.y = Y.new
somex.y.z = "this is the value of z in somex.y.z"
anotherx = X.new
anotherx.y = nil
puts somex.y.z
puts anotherx.y.z
puts anotherx.y.z.a.b.c
# ... there may be a way to do what you want in a more elegant manner. i don't know off-hand, though.
# hope this helps a little, at least.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.