Slightly Surprising Class Method Interaction

I encountered something in rails today that I haven’t seen before. It was clearly a ruby feature, so I wrote up an example in ruby. It’s an attempt to access a private instance method from both a public class method and a public instance method:

You have a class:

class SimpleClass
def self.stuff
"Private method returns #{private_stuff}"

def things
"Private method returns #{private_stuff}"

def private_stuff


I expected that in both cases, I’d get the string out:

Private method returns content

However, it turns out these are different. The instance variable version returns the output as expected. The class method?

undefined local variable or method `private_stuff' for SimpleClass:Class (NameError)

So, class methods cannot access private instance methods.

The rule in general is that a private method cannot have an explicit receiver. I am left wondering if a class method has an explicit receiver, and I’m just not seeing it.

Edit: hah! I was wrong in my supposition about an explicit receiver. The issue is that class methods are defined in the eigenclass, which is a step in the inheritance hierarchy above the current class and as such cannot access private methods in the current class.

This brings up the richer point: can a public instance method be accessed from within a class method? I’m betting on no.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s