Jwan622 Jwan622 - 3 months ago 7
Ruby Question

Ruby class methods. Is it getting called on main object?

I have a class that looks like this:

class Test
def self.hello
puts "I say hello"
end

def goodbye
puts 'goodbye'
end

hello
goodbye
end


This is my output:

ruby class_methods.rb
I say hello
class_methods.rb:11:in `<class:Test>': undefined local variable or method `goodbye' for Test:Class (NameError)
from class_methods.rb:1:in `<main>'


What is
hello
being called on? It looks like it does indeed get called but what is it being called on? I think it's being called on the main object... but why does that make sense? I thought class methods can only be called on the class object itself not a
main
object?

Answer

What is hello being called on?

Whenever there isn't an explicit receiver, the receiver is self. So the call is implicitly:

self.hello

... where self is the class Test, on which you have just defined the self.hello method.

goodbye is not found because it is defined on an instance of class Test, not the class itself, where it's currently called.