Ruby中的运算符(Operators in Ruby)

编程入门 行业动态 更新时间:2024-10-26 06:26:20
Ruby中的运算符(Operators in Ruby)

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 end

This 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" end

Preceding a constant with :: means that you take it from the outer, or global, scope.

更多推荐

本文发布于:2023-04-29 06:51:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1335262.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:运算符   Ruby   Operators

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!