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

Ruby

Ruby Problem Overview


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()

Ruby Solutions


Solution 1 - Ruby

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionflyingarmadilloView Question on Stackoverflow
Solution 1 - RubyalexView Answer on Stackoverflow