2

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.

Marc-André Lafortune
  • 78,216
  • 16
  • 166
  • 166
OneZero
  • 11,556
  • 15
  • 55
  • 92

2 Answers2

4

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.

tadman
  • 208,517
  • 23
  • 234
  • 262
3

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
evfwcqcg
  • 15,755
  • 15
  • 55
  • 72