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 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"]
Module
self
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:
self
is the receiver of the methodself
is the class or module object being definedself
is bound to the class when class_eval
'd and bound to the object when instance_eval
'd