.vs ::(点与双冒号)用于调用方法

fly*_*llo 45 ruby

可能重复:
Ruby中的含义是什么意思?

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

File::open( 'idea-' + idea_name + '.txt', 'w' ) do |f|
   f << idea
end
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,双冒号用于访问类的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 
Run Code Online (Sandbox Code Playgroud)

这次,使用点来访问类的read方法File.有什么区别:

File.read()
Run Code Online (Sandbox Code Playgroud)

File::open()
Run Code Online (Sandbox Code Playgroud)

ale*_*lex 29

它是范围解析运算符.

维基百科的一个例子:

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.
Run Code Online (Sandbox Code Playgroud)

  • ::和之间没有区别.在函数中调用类(静态)方法时.但是你可以使用::来访问常量和其他命名空间的东西,你不能使用dot.我个人一直使用dot,但我的同事使用::来调用静态方法.当你调用名字空间的东西时,也许它在某种程度上更美观,比如Foo :: Bar :: open(而不是Foo :: Bar.open),但它的工作方式相同.表现也一样.PS这里讨论的主题很好:https://www.ruby-forum.com/topic/107527 (34认同)
  • 这没有回答这个问题:"File.read()`和`File :: open()`之间的区别是什么?".为什么两者都可以用来调用方法?我们何时会选择一个而不是另一个? (23认同)