Search code examples
rubyself

What are the rules for `self` in a top-level method?


If I define a top-level method in a Ruby file, the value of self seems to depend heavily on who is calling it.

def who_am_i
  puts self.inspect
end

class A
  def self.foo
    who_am_i
  end
  def foo
    who_am_i
  end
end

def foo
  who_am_i
end

foo       # >> main
A.foo     # >> A
A.new.foo # >> #<A:...>

Obviously, if a method is defined in a class, self will either be the class itself (for class methods) or the relevant instance of the class (for instance methods). It seems, based on the trials shown above, that a method not defined in a class inherits self from its caller, but I can't find any official reference or anything to back that up. Can someone provide an official source that describes this behavior and ideally a rationale for why it works this way?


Solution

  • All methods defined in the context of main object, will become [private] methods on Object. And since everything is an Object, this method will be available everywhere. And this is also why self is changing based on where you call it from: those are all different objects, but they also all inherit this method.

    private_methods.include?(:who_am_i) # => true
    foo       # => "main"
    A.private_methods.include?(:who_am_i) # => true
    A.foo    # => "A"
    A.new.private_methods.include?(:who_am_i) # => true
    A.new.foo # => "#<A:0x00007feaad034e00>"