简体   繁体   English

“内核”的目的是什么?

[英]What is the purpose of `Kernel`?

  1. What is the purpose of the Kernel module? Kernel模块的目的是什么? What would change if all the things currently defined on Kernel were defined on Object , and there were no such module as Kernel ? 如果在Kernel上定义的所有内容都是在Object上定义的,并且没有像Kernel这样的模块,会发生什么变化?
  2. When I want to define a method that can be called on any object, should I define that on Kernel or on Object ? 当我想定义一个可以在任何对象上调用的方法时,我应该在KernelObject上定义它吗?

I'll start with a question: what would self be inside a typical Kernel method such as puts ? 我将从一个问题开始:在一个典型的Kernel方法(例如puts会有什么样的self The closest thing to a meaningful self inside puts would probably be the Ruby runtime itself. 最有意义的self内部puts可能是Ruby运行时本身。 Similarly for other "methods that really want to be functions" like Array or fork . 类似于其他“真正想成为函数的方法”,如Arrayfork So you can look at Kernel as a dumping ground for methods that are, more or less, commands or messages to Ruby itself. 因此,您可以将Kernel视为一种倾向,这些方法或多或少是Ruby本身的命令或消息。

Kernel also has odd methods like sub and chop that are really only useful for one-off ruby -e scripts. Kernel也有奇怪的方法,如subchop ,它们只对一次性ruby -e脚本有用。 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. 这些东西倾向于使用$_作为隐含的self但我认为它们可以被视为上面“Ruby运行时命令”的特殊情况。

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 . 我会说它会进入Object If the method is really a function in disguise and has no meaningful self , then it would go into Kernel . 如果该方法实际上是伪装的函数并且没有有意义的self ,那么它将进入Kernel

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM