Explain private methods?

G

Gaba Luschi

Hi,
When you use the word "private" to clear private methods - what does it
mean that only code within the object's methods can access those private
methods? Can someone give me a simple example of this?

Thanks!
 
B

Ben Bleything

When you use the word "private" to clear private methods - what does it
mean that only code within the object's methods can access those private
methods? =A0Can someone give me a simple example of this?

That's basically correct, yes. Technically it means that the method
cannot be called with an explicit receiver:

class Foo
def pub
return "public method"
end

def call_priv
priv
end

def call_priv_explicitly
self.priv
end

private
def priv
return "private method"
end
end

f =3D Foo.new
f.pub
# =3D> "public method"

f.priv
# =3D> private method `priv' called for #<Foo:0x10016a1b0> (NoMethodError)

f.call_priv
# =3D> "private method"

f.call_priv_explicitly
# =3D> private method `priv' called for #<Foo:0x100169b98> (NoMethodError)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top