def vs. define_method

Updated . Posted . Visible to the public.

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

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
Profile picture of Dominik Schöler
Dominik Schöler
Last edit
Dominik Schöler
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2013-03-22 13:36)