我正在学习 Ruby令人心酸的 Ruby 指南 http://www.rubyinside.com/media/poignant-guide.pdf在一些代码示例中,我遇到了双冒号和点的使用,它们似乎用于相同的目的:
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()
and
File::open()
这是范围解析运算符 http://en.wikipedia.org/wiki/Scope_resolution_operator#Ruby.
维基百科的一个例子:
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.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)