def vs. define_method
Ever wondered about the difference between
define_method? Turns out there are
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 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"]
- A method defined in
- Defines an instance method on the receiver; implicit receiver is
- 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
self is the "current object" and implicit receiver of method calls:
- in a method body,
selfis the receiver of the method
- in a class or module definition,
selfis the class or module object being defined
- in blocks,
selfis bound to the class when
class_eval'd and bound to the object when