红宝石- vs::(点与双冒号),用于调用方法

这个问题已经在这里有了答案:

  • Ruby的双冒号`::`是什么? 10个答案
  • ::(双冒号)在Ruby中是什么意思? [重复] 3个答案
  • Ruby的双冒号(::)运算符用法差异 2个答案

我正在从《 Poignant Ruby指南》中学习Ruby,在一些代码示例中,我遇到了双冒号和点的用法,这些用法似乎用于相同的目的:

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

在上面的代码中,双冒号用于访问File类的read方法。 但是,我后来遇到了出于相同目的使用点的代码:

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 

这次,使用了一个点来访问File类的read方法。 之间有什么区别?

File.read()

File::open()
flyingarmadillo asked 2020-07-11T13:35:17Z
1个解决方案
29 votes

它是范围解析运算符。

维基百科的一个例子:

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.
alex answered 2020-07-11T13:35:34Z
translate from https://stackoverflow.com:/questions/11043450/vs-dot-vs-double-colon-for-calling-a-method