I am learning Ruby from the Poignant Guide to Ruby and in some of the code examples, I came across uses of the double colon and dot that seem to be used for the same purpose:
File::open( 'idea-' + idea_name + '.txt', 'w' ) do |f|
f << idea
end
In the above code, the double colon is being used to access the open
method of the File
class. However, I later came across code that used a dot for the same purpose:
require 'wordlist'
# Print each idea out with the words fixed
Dir['idea-*.txt'].each do |file_name|
idea = File.read( file_name )
code_words.each do |real, code|
idea.gsub!( code, real )
end
puts idea
end
This time, a dot is being used to access the read
method of the File
class. What is the difference between:
File.read()
and
File::open()
The double colon (::) operator, also known as method reference operator in Java, is used to call a method by referring to it with the help of its class directly. They behave exactly as the lambda expressions.
The :: is a unary operator that allows: constants, instance methods and class methods defined within a class or module, to be accessed from anywhere outside the class or module.
Two colons (::) are used in C++ as a scope resolution operator. This operator gives you more freedom in naming your variables by letting you distinguish between variables with the same name.
There are two distinct ways to access methods in PHP, but what's the difference? sfConfig::set('foo', 'bar'); I'm assuming -> (dash with greater than sign or chevron) is used for functions for variables, and :: (double colons) is used for functions for classes.
It's the scope resolution operator.
An example from Wikipedia:
module Example
Version = 1.0
class << self # We are accessing the module's singleton class
def hello(who = "world")
"Hello #{who}"
end
end
end #/Example
Example::hello # => "Hello world"
Example.hello "hacker" # => "Hello hacker"
Example::Version # => 1.0
Example.Version # NoMethodError
# This illustrates the difference between the message (.) operator and the scope
# operator in Ruby (::).
# We can use both ::hello and .hello, because hello is a part of Example's scope
# and because Example responds to the message hello.
#
# We can't do the same with ::Version and .Version, because Version is within the
# scope of Example, but Example can't respond to the message Version, since there
# is no method to respond with.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With