Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
# 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)
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
class X
attr_accessor :y
class Y
attr_accessor :z
class Z
attr_accessor :foo
require 'ostruct'
somex =
somex.y =
somex.y.z = "this is the value of z in somex.y.z"
anotherx =
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