简体   繁体   中英

What is the purpose of `Kernel`?

  1. What is the purpose of the Kernel module? What would change if all the things currently defined on Kernel were defined on Object , and there were no such module as 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 ?

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 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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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