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.
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.
Copy$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 indefine_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 whenclass_eval
'd and bound to the object wheninstance_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).