I got completely lost about the self
keyword. How does it change when we enter into a module, class, method, block, or everything else? Can anyone give me a summary?
Here I'm asking how does self change along execution instead of what self means.
I got completely lost about the self
keyword. How does it change when we enter into a module, class, method, block, or everything else? Can anyone give me a summary?
Here I'm asking how does self change along execution instead of what self means.
Unlike JavaScript where this
might refer to any number of things, in Ruby self
always refers to the execution context of the current method.
Within a class
method, self
will refer to the class itself:
class FooClass
def self.bar
self # => FooClass
end
end
Within a class
instance method, self
will refer to the instance:
class FooClass
def bar
self # => This instance (FooClass#nnnn)
end
end
Within a module
method, self
may refer to the module:
module FooModule
def self.bar
self # => FooModule
end
end
When a module method is mixed in via include
it will refer to an instance:
module FooModule
def bar
self # => (Depends on included context)
end
end
class BarClass
include FooModule
def foo
bar # => This instance (BarClass#nnnn)
end
end
The only tricky part is modules, and they're only tricky because other things can include them. The way to remember it best is self
generally refers to the thing on the left-hand side of the dot. That is my_object.foo
means self
is my_object
in the immediate context of that method.
There are ways of re-defining self
within the context of a block by using instance_eval
and class_eval
type operations, or class << self
declarations to manipulate the eigenclass.
self
always refers to the current object.
class A
p self # => A
def foo
p self # => instance of A
end
end
module M
p self # => M
end
A.new.foo