I want to do something but I’m not sure if it is possible. I want to use “generic methods” or “default methods” in case when some method is called but is not defined. This is a simple example so you can understand my point:
This is the class:
class XYZ
def a
#...
end
def b
#...
end
end
The instance of the class XYZ:
n = XYZ.new
n.a
n.b
n.c
As you can see, I’m calling the method “c” which is not defined and it will throw an error. Can I do something in the class XYZ so when someone calls a method not defined get the name of the method and do something, in base of the name of the method? And, is this possible in another languages (not making a compiler)? If this is possible, how is it called (theory speaking)?
Use
method_missing:You should also define
respond_to_missing?to getrespond_to?to work nicer in 1.9.2+. You should read more aboutrespond_to?/respond_to_missing?when usingmethod_missing.This, by the way, would be considered to be metaprogramming. This isn’t typically possible in compiled languages because of the way they call functions.