How come I can say
Math.sqrt(4)
or
Math::sqrt(4)
but I can't say
Math.PI
in ruby
What is the difference between what the dot operator is doing and the colon operator in this case?
How come I can say
Math.sqrt(4)
or
Math::sqrt(4)
but I can't say
Math.PI
in ruby
What is the difference between what the dot operator is doing and the colon operator in this case?
. is message passing operator and :: is scope resolution operator in Ruby. see the below example:
module Foo
X = 12
def self.bar
p "hi"
end
end
Foo::bar # => "hi"
Foo.bar # => "hi"
Foo::X # => 12
Foo.X
# undefined method `X' for Foo:Module (NoMethodError)
In Ruby you can call class or module methods(which can be called by the class/module name itself) like bar using the . and :: also. But the constants like X should need to be called using ::,but . is not allowed.In your case sqrt is a class method of the module Math,whereas PI is a constant of the module Math.