Ruby 中的 Object 和 BasicObject 有什么区别? [英] What's the difference between Object and BasicObject in Ruby?

查看:39
本文介绍了Ruby 中的 Object 和 BasicObject 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这些类有什么区别?它们的目的有什么区别?

解决方案

BasicObject 是在 Ruby 1.9 中引入的,它是 Object 的父级(因此 BasicObject 是 Ruby 中所有类的父类).

BasicObject 本身几乎没有方法:

<块引用>

::new#!#!=#==#__ID__#__发送__#平等的?#instance_eval#instance_exec

<小时><块引用>

BasicObject 可用于创建独立于Ruby 的对象层次结构,代理对象,如 Delegator 类,或来自 Ruby 方法和类的命名空间污染的其他用途必须避免.

BasicObject 不包括内核(对于像 puts 这样的方法)和BasicObject 在标准库的命名空间之外,所以如果不使用完整的类路径,将无法找到公共类.

<小时><块引用>

Object 混入 Kernel 模块,使得内置内核功能可全局访问.虽然 Object 的实例方法由内核模块定义...

您可以使用 BasicObject 作为对象的父对象,以防万一您不需要 Object 的方法,否则您将取消定义它们:

#当你继承Object时类示踪剂instance_methods.each 做 |m|下一个 if [:__id__, :__send__].include?米undef_method m结尾# 一些逻辑结尾# 当你继承 BasicObject 时类示踪剂<基本对象# 一些逻辑结尾

What's the difference between these classes? What's the difference between their purposes?

解决方案

BasicObject was introduced in Ruby 1.9 and it is a parent of Object (thus BasicObject is the parent class of all classes in Ruby).

BasicObject has almost no methods on itself:

::new
#!
#!=
#==
#__id__
#__send__
#equal?
#instance_eval
#instance_exec


BasicObject can be used for creating object hierarchies independent of Ruby's object hierarchy, proxy objects like the Delegator class, or other uses where namespace pollution from Ruby's methods and classes must be avoided.

BasicObject does not include Kernel (for methods like puts) and BasicObject is outside of the namespace of the standard library so common classes will not be found without a using a full class path.


Object mixes in the Kernel module, making the built-in kernel functions globally accessible. Although the instance methods of Object are defined by the Kernel module...

You can use BasicObject as a parent of your object in case if you don't need methods of Object and you would undefine them otherwise:

# when you inherit Object
class Tracer
  instance_methods.each do |m|
    next if [:__id__, :__send__].include? m
    undef_method m
  end

  # some logic
end

# when you inherit BasicObject
class Tracer < BasicObject
  # some logic
end

这篇关于Ruby 中的 Object 和 BasicObject 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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