ruby如何允许一个方法和一个同名的Class? [英] How does ruby allow a method and a Class with the same name?
问题描述
Factory.create(...)
和短路 工厂(...)
我想到了,很好奇,看看他们如何让课程工厂
也表现像一个方法一样。 他们只是简单地使用工厂
两次:
def工厂(args)
...
结束
类工厂
...
end
我的问题是: Ruby是如何实现的?使用这个看似古怪的模式有危险吗?
方法和变量生活在不同的命名空间中。所以,你可以同时使用一个方法和一个变量(在这种情况下是一个常量)。然而,在使用它们时,Ruby需要能够区分它们。一般来说,这不是一个问题:消息有接收器,变量不。消息有参数,变量不。变量被分配到,消息不是。
唯一的问题是当你没有接收者,没有参数和没有任务。然后,Ruby不能区分发送无参数的无接收器消息和变量。所以,它必须构成一些任意的规则,这些规则基本上是:
- 对于以小写字母开头的模糊标记,更喜欢将其解释为消息发送,除非您肯定知道它是一个变量(即解析器(不是(!)解释器)之前已经看过一个赋值) li>
- 以大写字母开头的模糊标记,更喜欢将其解释为常数。
注意对于使用参数发送的消息(即使参数列表为空),也没有歧义。
-
test()
:显然是一个消息发送,没有歧义这里 -
test
:可能是一个消息发送或变量;解决规则说这是一个消息发送(除非已经有一个赋值给test
before) -
Test ()
:显然是一个消息发送,这里没有歧义 -
self.Test
: 显然是一个消息发送,没有歧义这里 -
测试
:可能是一个消息发送或常量;解决规则说这是一个常数
I happened to be working on a Singleton class in ruby and just remembered the way it works in factory_girl. They worked it out so you can use both the long way Factory.create(...)
and the short way Factory(...)
I thought about it and was curious to see how they made the class Factory
also behave like a method.
They simply used Factory
twice like so:
def Factory (args)
...
end
class Factory
...
end
My Question is: How does ruby accomplish this? and Is there danger in using this seemingly quirky pattern?
Methods and variables live in different namespaces. So, you can have both a method and a variable (or in this case a constant) with the same name. However, when using them, Ruby needs to be able to distinguish between them. In general, that's not a problem: messages have receivers, variables don't. Messages have arguments, variables don't. Variables are assigned to, messages aren't.
The only problem is when you have no receiver, no argument and no assignment. Then, Ruby cannot tell the difference between a receiverless message send without arguments and a variable. So, it has to make up some arbitrary rules, and those rules are basically:
- for an ambiguous token starting with a lowercase letter, prefer to interpret it as a message send, unless you positively know it is a variable (i.e. the parser (not(!) the interpreter) has seen an assignment before)
- for an ambiguous token starting with an uppercase letter, prefer to interpret it as a constant
Note that for a message send with arguments (even if the argument list is empty), there is no ambiguity.
test()
: obviously a message send, no ambiguity heretest
: might be a message send or a variable; resolution rules say it is a message send (unless there has been an assignment totest
before)Test()
: obviously a message send, no ambiguity hereself.Test
: also obviously a message send, no ambiguity hereTest
: might be a message send or a constant; resolution rules say it is a constant
这篇关于ruby如何允许一个方法和一个同名的Class?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!