Defining methods on instances

suggest change

In Ruby you can add methods to an existing instance. That changes one object without changing the other instances of its class. Use define_singleton_method. define_method is private on the class and would define a method for every instance.

class Example
  def method1(foo)
    puts foo
  end
end

# defines method2 on the object exp only
exp = Example.new
exp.define_singleton_method(:method2) { puts "Method2" }

# with method parameters
exp.define_singleton_method(:method3) { |name| puts name }

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents