“内核"的目的是什么? [英] What is the purpose of `Kernel`?
问题描述
-
Kernel
模块的目的是什么?如果当前在Kernel
上定义的所有内容都在Object
上定义,并且没有诸如Kernel
这样的模块,将会发生什么变化? - 当我想定义一个可以在任何对象上调用的方法时,我应该在
Kernel
还是Object
上定义它?
- What is the purpose of the
Kernel
module? What would change if all the things currently defined onKernel
were defined onObject
, and there were no such module asKernel
? - When I want to define a method that can be called on any object, should I define that on
Kernel
or onObject
?
推荐答案
我将从一个问题开始:self
在典型的 Array
或 fork
.因此,您可以将Kernel
视为方法的垃圾场,这些方法或多或少是发给Ruby本身的命令或消息.
I'll start with a question: what would self
be inside a typical Kernel
method such as puts
? The closest thing to a meaningful self
inside puts
would probably be the Ruby runtime itself. Similarly for other "methods that really want to be functions" like Array
or fork
. So you can look at Kernel
as a dumping ground for methods that are, more or less, commands or messages to Ruby itself.
Kernel
也具有诸如 sub
和 chop
仅对一次性ruby -e
脚本.这些东西倾向于使用$_
作为隐含的self
,但是我认为它们可以被视为上述"Ruby运行时命令"的特殊情况.
Kernel
also has odd methods like sub
and chop
that are really only useful for one-off ruby -e
scripts. These things tend to use $_
as an implied self
but I think they can be considered as special cases of the "commands to the Ruby runtime" as above.
当您希望能够在任何对象上调用该方法时,该方法会去哪儿?我会说它将进入Object
.如果该方法确实是伪装的函数并且没有有意义的self
,则它将进入Kernel
.
Where does a method go when you want to be able to call that method on any object? I'd say that it would go into Object
. If the method is really a function in disguise and has no meaningful self
, then it would go into Kernel
.
这篇关于“内核"的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!