newbie question: symbol to fully qualify a method: #, ::, .

S

seannakasone

I'm a newbie. I'm going through the ruby documentation and I noticed
there's 3 different separators (#, ::, .) used to fully qualify a
method in a class or module.

i.e.
MyClass.myproc
MyClass#myproc
MyClass::myproc

What's the difference?
 
D

dave.burt

I'm a newbie. I'm going through the ruby documentation and I noticed
there's 3 different separators (#, ::, .) used to fully qualify a
method in a class or module.

i.e.
MyClass.myproc
MyClass#myproc
MyClass::myproc

What's the difference?

MyClass::myproc -- myproc is a class method, called either of these two
ways:

MyClass::myproc
MyClass.myproc

MyClass#myproc -- myproc is an instance method, belonging to instances
of MyClass:

my_obj = MyClass.new
my_obj.myproc

MyClass.myproc probably means the same as MyClass::myproc.

Cheers,
Dave
 
J

JimC

The difference between the "." and "::" forms arises when the method
name starts with a capital letter and has to do with how Ruby figures
out what you're trying to do at runtime. Using your example above, the
"." and "::" forms are the same.

But, if you change myproc to Myproc, there is a difference. Ruby will
assume that MyClass::Myproc is an attempt to access a constant, and
that MyClass.Myproc, MyClass.Myproc(), and MyClass::Myproc() are
method invocations.

HTH,
Jim
 
M

Michael Perle

I'm a newbie. I'm going through the ruby documentation and I noticed
there's 3 different separators (#, ::, .) used to fully qualify a
method in a class or module.

i.e.
MyClass.myproc
MyClass#myproc
MyClass::myproc

What's the difference?

No a guru, but trying to post my first answer here:

MyClass.myproc
is a call to the class method myproc of class MyClass.

MyClass#myproc
does not exist in the syntax, but is used in Ruby
documentation to differentiate the call of an
instance method from the call of a class method.
In fact it means MyClass.new.myproc or more generic
myInstance.myproc where myInstance is an instance
of MyClass.

MyClass::myproc
means the function or method myproc in the name space
MyClass. MyClass could be a class context or a module
or whatsoever.
 
S

seannakasone

Thanks guys, it was all helpful.

Michael, thanks for explaining that # was only a documentation aide.
To me that was sort of a pitfall.
 

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

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top