Jwan622 Jwan622 - 1 year ago 67
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"

def goodbye
puts 'goodbye'


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
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

Answer Source

What is hello being called on?

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


... 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download