Ruby中的点运算符,冒号运算符和范围解析运算符有什么区别?
他们在哪里和为什么使用?
What is the difference in dot operator, colon operator and scope resolution operator in Ruby?
Where and why are they used?
最满意答案
点运算符分隔属于该对象的对象和方法,例如"Hello".reverse或
def self.my_singleton_method end这个单一的冒号并不是真正的运营商。 它可以在ruby 1.8中使用,而不是在if或case/when语句中使用。 在ruby 1.9中,它可以用于散列文字,例如{A : 65} 。 它在一个标识符之前形成一个符号,例如:red ,它用在三元条件操作符?: 。
双冒号操作符是范围解析操作符。 它指定在哪个类或模块中引用常量。 请注意,类和模块本身是常量。
module MyModule class Object end p Object # prints "MyModule::Object" p ::Object # prints "Object" end在::之前加一个常数意味着你从外部或全局范围中取得它。
The dot operator separates an object and a method belonging to that object, for example "Hello".reverse or
def self.my_singleton_method endThis single colon isn't really an operator. It can be used in ruby 1.8 instead of then in an if or case/when statement. In ruby 1.9 it can be used in hash literals, e.g. {A : 65}. It precedes an identifier to form a Symbol, e.g. :red, and it's used in the ternary condition operator ?:.
The double colon operator is the scope resolution operator. It specifies in which class or module you reference a constant. Note that classes and modules are themselves constants.
module MyModule class Object end p Object # prints "MyModule::Object" p ::Object # prints "Object" endPreceding a constant with :: means that you take it from the outer, or global, scope.
更多推荐
发布评论