Advertisement
Advertisement


Is there a difference between :: and . when calling class methods in Ruby?


Question

Simple question, but one that I've been curious about...is there a functional difference between the following two commands?

String::class
String.class

They both do what I expect -- that is to say they return Class -- but what is the difference between using the :: and the .?

I notice that on those classes that have constants defined, IRB's auto-completion will return the constants as available options when you press tab after :: but not after ., but I don't know what the reason for this is...

2008/09/04
1
25
9/4/2008 3:21:31 AM

Accepted Answer

The . operator basically says "send this message to the object". In your example it is calling that particular member. The :: operator "drills down" to the scope defined to the left of the operator, and then calls the member defined on the right side of operator.

When you use :: you have to be referencing members that are defined. When using . you are simply sending a message to the object. Because that message could be anything, auto-completion does not work for . while it does for ::.

2008/09/04
36
9/4/2008 2:08:10 PM


Source: https://stackoverflow.com/questions/43134
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]