define method for instance of class

Posted by aharon on Stack Overflow See other posts from Stack Overflow or by aharon
Published on 2010-06-11T23:53:56Z Indexed on 2010/06/12 0:03 UTC
Read the original article Hit count: 201

Filed under:

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?

Thanks so much.

© Stack Overflow or respective owner

Related posts about ruby