.vs :: (dot vs. double-colon) 用于调用方法 [英] . vs :: (dot vs. double-colon) for calling a method
本文介绍了.vs :: (dot vs. double-colon) 用于调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在从 Poignant Guide to Ruby 和一些在代码示例中,我遇到了似乎用于相同目的的双冒号和点的用法:
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
在上面的代码中,双冒号用于访问File
类的open
方法.但是,我后来遇到了出于相同目的使用点的代码:
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
这一次,使用一个点来访问File
类的read
方法.有什么区别:
This time, a dot is being used to access the read
method of the File
class. What is the difference between:
File.read()
和
File::open()
推荐答案
维基百科的一个例子:
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.
这篇关于.vs :: (dot vs. double-colon) 用于调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文