Skip to content

Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →

instance method

Module#define_method

(::interned symbol, ^() [self: instance] -> untyped | ::Method | ::UnboundMethod method) -> ::Symbol
(::interned symbol) { () [self: instance] -> untyped } -> ::Symbol
define_method(symbol, method) → symbol
define_method(symbol) { block } → symbol

Defines an instance method in the receiver. The method parameter can be a Proc, a Method or an UnboundMethod object. If a block is specified, it is used as the method body. If a block or the method parameter has parameters, they’re used as method parameters. This block is evaluated using instance_eval.

Example
class A
  def fred
    puts "In Fred"
  end
  def create_method(name, &block)
    self.class.define_method(name, &block)
  end
  define_method(:wilma) { puts "Charge it!" }
  define_method(:flint) {|name| puts "I'm #{name}!"}
end
class B < A
  define_method(:barney, instance_method(:fred))
end
a = B.new
a.barney
a.wilma
a.flint('Dino')
a.create_method(:betty) { p self }
a.betty

produces:

In Fred
Charge it!
I'm Dino!
#<B:0x401b39e8>