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?