Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

. vs :: (dot vs. double-colon) for calling a method [duplicate]

Tags:

ruby

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()
like image 945
flyingarmadillo Avatar asked Jun 15 '12 01:06

flyingarmadillo


People also ask

What does the double colon :: operator do in a class?

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.

What does :: In rails mean?

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.

What is double colon in C++?

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.

What's the difference between double colon and arrow in PHP?

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.


1 Answers

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.
like image 104
alex Avatar answered Oct 17 '22 13:10

alex