Aaron Yodaiken Aaron Yodaiken - 4 months ago 7
Ruby Question

define method for instance of class

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?

Answer

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