Posted over 9 years ago. Visible to the public.

def vs. define_method

Ever wondered about the difference between def and define_method? Turns out there are three implicit contexts Archive 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

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 end 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

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for unsupported versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2).

Owner of this card:

Dominik Schöler
Last edit:
about 6 years ago
by Dominik Schöler
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Dominik Schöler to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more