::MyClass Ruby 作用域运算符有什么作用? [英] What does ::MyClass Ruby scope operator do?
本文介绍了::MyClass Ruby 作用域运算符有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
::MyClass/MyModule
作用域运算符在 Ruby 中有什么作用,它的用途是什么?
What does the ::MyClass/MyModule
scope operator do in Ruby, what is its purpose?
推荐答案
这在全局范围内显式引用 MyClass.如果全局作用域中有MyClass,SomeModule内部也有MyClass,则SomeModule内部引用MyClass会引用模块内部的MyClass,而不是全局MyClass.说 ::MyClass 明确引用全局范围内的 MyClass.
This explicitly refers to the MyClass in the global scope. If there is a MyClass in the global scope, but also a MyClass inside of SomeModule, referring to MyClass from inside of SomeModule will refer to MyClass inside of the module, not the global MyClass. Saying ::MyClass explicitly refers to the MyClass in the global scope.
class MyClass
def self.something
puts "Global MyClass"
end
end
module SomeModule
class MyClass
def self.something
puts "SomeModule::MyClass"
end
end
print "From the module: "
MyClass.something
print "Explicitly using global scope: "
::MyClass.something
end
print "From the global scope: "
MyClass.something
print "Explicitly using module scope: "
SomeModule::MyClass.something
这篇关于::MyClass Ruby 作用域运算符有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文