Ruby: Add a method to the class of an input parameter
- by TJB
I'm just exploring ruby and was wondering about the theoretical possibility of adding a method to the class of an object. For example, define a method that takes in a parameter and would add a method to the class of that parameter (not just to the parameter object itself). Something like this example:
class SomeClass
end
class AnotherClass
end
alpha = SomeClass.new
beta = AnotherClass.new
def AddHelloMethodTo param
# This is where I'm trying to
# add a method to the class of the parameter
def param.class.Hello
"Hello"
end
end
AddHelloMethodTo alpha
AddHelloMethodTo beta
gamma = AnotherClass.new
alpha.Hello
beta.Hello
gamma.Hello
(Excuse me if I have syntax errors / typos I'm REALLY new to this!)
Notice how I don't call the AddHelloMethodTo on gamma but I expect Hello to be defined because I added it to the class.
Is this possible?