且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Ruby 中的 Object 和 BasicObject 有什么区别?

更新时间:2023-11-06 10:22:04

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