Подтвердить что ты не робот

, vs:: (точка против двойной двоеточия) для вызова метода

Я изучаю Ruby из Poignant Guide to Ruby, и в некоторых примерах кода я сталкивался с использованием двойного двоеточия и точки, которые, кажется, используются для той же цели:

File::open( 'idea-' + idea_name + '.txt', 'w' ) do |f|
   f << idea
end

В приведенном выше коде двойное двоеточие используется для доступа к методу open класса File. Однако позже я наткнулся на код, который использовал точку для той же цели:

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 

На этот раз точка используется для доступа к методу read класса File. В чем разница между:

File.read()

а также

File::open()
4b9b3361

Ответ 1

Это оператор разрешения области видимости.

Пример из Википедии:

module Example
  Version = 1.0

  class << self # We are accessing the module 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 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.