Read more

def vs. define_method

Dominik Schöler
March 22, 2013Software engineer at makandra GmbH

Ever wondered about the difference between def and define_method? Turns out there are three implicit contexts Show snapshot in Ruby. def and define_method differ in which one they use.


  • Ruby keyword, starts a method definition
  • Opens a new, isolated scope. Variables defined outside are not accessible inside and vice versa.
  • Defines an instance method on the receiver (specified before the method name, e.g. def; implicit receiver is the default definee
Illustration money motivation

Opscomplete powered by makandra brand

Save money by migrating from AWS to our fully managed hosting in Germany.

  • Trusted by over 100 customers
  • Ready to use with Ruby, Node.js, PHP
  • Proactive management by operations experts
Read more Show snapshot

The default definee is not self and cannot be changed or passed around, but is determined syntactically.

$string = "hello world"
class Foo  
  def $string.baz # define a singleton method on $string / an instance method on $string's singleton class
    def bar; end
Foo.instance_methods(false) # => ["bar"]
$string.methods(false) # => ["baz"]


  • A method defined in Module
  • Defines an instance method on the receiver; implicit receiver is self
  • Takes a block as method body, which is evaluated using instance_eval. Since blocks carry with them the binding in which they were created, variables from outside are accessible in define_method.

self is the "current object" and implicit receiver of method calls:

  • in a method body, self is the receiver of the method
  • in a class or module definition, self is the class or module object being defined
  • in blocks, self is bound to the class when class_eval'd and bound to the object when instance_eval'd
Posted by Dominik Schöler to makandra dev (2013-03-22 14:36)