Let there be class Example
defined as:
class Example def initialize(test='hey') self.class.send(:define_method, :say_hello, lambda { test }) end end
On calling Example.new; Example.new
I get a warning: method redefined; discarding old say_hello
. This, I conclude, must be because it defines a method in the actual class (which makes sense, from the syntax). And that, of course, would prove disastrous should there be multiple instances of Example
with different values in their methods.
Is there a way to create methods just for the instance of a class from inside that instance?
In Ruby, a method provides functionality to an Object. A class method provides functionality to a class itself, while an instance method provides functionality to one instance of a class. We cannot call an instance method on the class itself, and we cannot directly call a class method on an instance.
class . There are no "static methods" in the C# sense in Ruby because every method is defined on (or inherited into) some instance and invoked on some instance. Accordingly, they can access whatever instance variables happen to be available on the callee.
Key TakeawaysInstance methods need a class instance and can access the instance through self . Class methods don't need a class instance. They can't access the instance ( self ) but they have access to the class itself via cls .
You need to grab a reference to the instance's singleton class, the class that holds all the instance specific stuff, and define the method on it. In ruby 1.8, it looks a little messy. (if you find a cleaner solution let me know!)
Ruby 1.8
class Example def initialize(test='hey') singleton = class << self; self end singleton.send :define_method, :say_hello, lambda { test } end end
Ruby 1.9 however, provides a much easier way in.
Ruby 1.9
class Example def initialize(test='hey') define_singleton_method :say_hello, lambda { test } end end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With