amindfv amindfv - 1 month ago 6
Ruby Question

Ruby method like `self` that refers to instance

Is there a method in Ruby that refers to the current instance of a class, in the way that

self
refers to the class itself?

Answer

self always refers to an instance, but a class is itself an instance of Class. In certain contexts self will refer to such an instance.

class Hello
  # We are inside the body of the class, so `self`
  # refers to the current instance of `Class`
  p self

  def foo
    # We are inside an instance method, so `self`
    # refers to the current instance of `Hello`
    return self
  end

  # This defines a class method, since `self` refers to `Hello`
  def self.bar
    return self
  end
end

h = Hello.new
p h.foo
p Hello.bar

Output:

Hello
#<Hello:0x7ffa68338190>
Hello