:: 和 . 之间有区别吗?在 Ruby 中调用类方法时? [英] Is there a difference between :: and . when calling class methods in Ruby?
问题描述
一个简单的问题,但我一直很好奇……以下两个命令之间是否存在功能差异?
Simple question, but one that I've been curious about...is there a functional difference between the following two commands?
String::class
String.class
他们都按照我的期望去做——也就是说他们返回Class
——但是使用::
和有什么区别.
?
They both do what I expect -- that is to say they return Class
-- but what is the difference between using the ::
and the .
?
我注意到在那些定义了常量的类上,当您在 ::
之后而不是在 之后按 Tab 键时,IRB 的自动补全会将常量作为可用选项返回.
,但我不知道这是什么原因...
I notice that on those classes that have constants defined, IRB's auto-completion will return the constants as available options when you press tab after ::
but not after .
, but I don't know what the reason for this is...
推荐答案
.
操作符基本上是说将此消息发送给对象".在您的示例中,它正在调用该特定成员.::
运算符向下钻取"到运算符左侧定义的范围,然后调用运算符右侧定义的成员.
The .
operator basically says "send this message to the object". In your example it is calling that particular member. The ::
operator "drills down" to the scope defined to the left of the operator, and then calls the member defined on the right side of operator.
当您使用 ::
时,您必须引用已定义的成员.使用 .
时,您只是向对象发送消息.因为该消息可以是任何内容,所以自动完成对 .
不起作用,而对 ::
起作用.
When you use ::
you have to be referencing members that are defined. When using .
you are simply sending a message to the object. Because that message could be anything, auto-completion does not work for .
while it does for ::
.
这篇关于:: 和 . 之间有区别吗?在 Ruby 中调用类方法时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!