Stefano Crocco
5/9/2007 6:52:00 PM
Alle mercoledì 9 maggio 2007, robninja@gmail.com ha scritto:
> Hi,
>
> I'm new to Ruby and throughly enjoying learning the language. I'm
> currently working my way through the Pickaxe book, but have a couple
> of questions I hope someone can help me out with.
>
> As I understand it the double-colon ( :: ) can be used when calling
> class methods or class constants, but could correctly be replaced by a
> single dot ( . ) if preferred:
>
> SongList::is_too_long(song1)
> SongList.is_too_long(song1)
>
> I was wondering if someone more experience could tell me which method
> is used by the majority of Rubyists and whether it is thought of as
> "best practice" to use the double colon?
>
> I suspect this is probably down to personal preference. I personally
> prefer the double-colon but I would like to get into good habits now
> whilst I'm learning the language. The Pickaxe book doesn't use ::
> except when referring to modules (not sure if that is the correct
> term), e.g.,
>
> class TestRoman < Test::Unit::TestCase
> #...
> end
>
> Could someone explain whether this is convention or if there is
> another reason for this?
>
> Many thanks!
> Robin
You need to use the double column when referring to a constant. You can use
either the double column or the dot when calling a method:
class C
CONST=1
def C.a_method
puts "a_method
end
end
C::a_method
=> "a_method"
C.a_method
=> "a_method"
puts C::CONST
=> 1
puts C.CONST
=> NoMetodError
In the last case, ruby is trying to find a class method of C named CONST
(because the dot can only be used to call a method). Since such a method
doesn't exist, a NoMethodError exception is raised. In the example of class
TestRoman, the double columns can't be replaced by dots because TestCase and
Unit are constants (respectively, a constant referring to a Module declared
in the Test module and a constant referring to a Class declared in the Unit
module).
As for which form is most used, I'm not an expert, but I think that the dot is
most used to call class methods.
Stefano