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}"
end

def things
"Private method returns #{private_stuff}"
end

private
def private_stuff
"content"
end
end

puts SimpleClass.new.things
puts SimpleClass.new.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.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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