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 archive.org snapshot in Ruby. def and define_method differ in which one they use.

def

  • 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 object.foo); implicit receiver is the default definee
Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org 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
  end  
end  
Foo.instance_methods(false) # => ["bar"]
$string.methods(false) # => ["baz"]

define_method

  • 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)