Ruby: Add a method to the class of an input parameter
        Posted  
        
            by 
                TJB
            
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by TJB
        
        
        
        Published on 2010-12-23T03:50:50Z
        Indexed on 
            2010/12/23
            3:54 UTC
        
        
        Read the original article
        Hit count: 369
        
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?
© Stack Overflow or respective owner