为什么Ruby模块内核存在? [英] Why does the Ruby module Kernel exist?

查看:52
本文介绍了为什么Ruby模块内核存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ruby中的OO Design 一书中,Sandi Metz说模块的主要用途是用它们实现鸭子类型,并将它们包含在每个需要的类中.为什么Ruby KernelObject中包含的模块?据我所知,它在其他任何地方都没有使用过.使用模块有什么意义?

In the book OO Design in Ruby, Sandi Metz says that the main use of modules is to implement duck types with them and include them in every class needed. Why is the Ruby Kernel a module included in Object? As far as I know it isn't used anywhere else. What's the point of using a module?

推荐答案

理想情况下,

  • 本质上的方法(适用于任何对象),即,使用接收方的方法应在Object类上定义,而
  • 过程(全局提供),即忽略接收者的方法,应收集在Kernel模块中.
  • Methods in spirit (that are applicable to any object), that is, methods that make use of the receiver, should be defined on the Object class, while
  • Procedures (provided globally), that is, methods that ignore the receiver, should be collected in the Kernel module.

Kernel#puts对其接收器不执行任何操作.它不会在其上调用私有方法,它不会访问其任何实例变量,而仅对其参数起作用.

Kernel#puts, for example doesn't do anything with its receiver; it doesn't call private methods on it, it doesn't access any instance variables of it, it only acts on its arguments.

使用Ruby的功能可以伪造Ruby中的过程,该功能可以忽略等于self的接收者.它们通常也被私有化,以防止它们被显式接收者调用,从而变得更加混乱.例如,"Hello".puts将打印换行符,而没有其他内容,因为puts仅关心其参数,而不关心其接收者.通过将其设为私有,只能将其称为puts "Hello".

Procedures in Ruby are faked by using Ruby's feature that a receiver that is equal to self can be omitted. They are also often made private to prevent them from being called with an explicit receiver and thus being even more confusing. E.g., "Hello".puts would print a newline and nothing else since puts only cares about its arguments, not its receiver. By making it private, it can only be called as puts "Hello".

实际上,由于Ruby的悠久历史,并非总是严格遵循这种分离.另外,由于某些Kernel方法在Object中进行了记录,反之亦然,并且进一步复杂的是,当您定义看起来像的全局过程时,还变得更加复杂.通过上述推理,该结果应最终在Kernel中,它实际上最终作为Object中的私有实例方法结束.

In reality, due to the long history of Ruby, that separation hasn't always been strictly followed. It is also additionally complicated by the fact that some Kernel methods are documented in Object and vice versa, and even further by the fact that when you define something which looks like a global procedure, and which by the above reasoning should then end up in Kernel, it actually ends up as a private instance method in Object.

这篇关于为什么Ruby模块内核存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆