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

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

在上面的代码中,双冒号用于访问File类的open方法.然而,我后来遇到了出于同样目的使用点的代码:

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

推荐答案

这是scope resolution operator.

维基百科的一个例子:

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.

Ruby相关问答推荐

ruby 3.1:使用方法(:名称)简化代码莫名其妙地失败

Ruby:对于不存在的键,使用缺省值Hash在Hash中存储Hash

扫描不带空格的字符串中的单词

Python 正则表达式是否等同于 Ruby 的原子分组?

Kernel#gets try 读取文件而不是标准输入

这些 Ruby 命名空间约定之间有什么区别?

CSV.read 第 x 行的非法引用

进程的 pid、ppid、uid、euid、gid 和 egid 有什么区别?

你喜欢哪种风格的 Ruby 字符串引用?

Ruby 中的 main是什么?

什么是匹配不在行尾的字符串的正则表达式?

RSpec:我如何在期望语法中使用数组包含匹配器

在本地覆盖 Vagrant 配置设置(每个开发人员)

如何修复错误的 URI 不是 URI

了解 ruby​​-prof 输出

判断散列的键是否包含所有键集

if语句末尾带有then有什么区别?

你怎么说不等于在 Ruby 中?

默认情况下需要查找的路径是什么?

Ruby Style:如何判断嵌套的哈希元素是否存在