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

标签 ruby ruby-1.9

这些类之间有什么区别?他们的目的有什么区别?

最佳答案

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

BasicObject 本身几乎没有方法:

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

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

# 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 - Ruby 中的 Object 和 BasicObject 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8894817/

相关文章:

ruby - gem install mongrel 使用 ruby​​ 1.9.1 失败

ruby - 为什么 Ruby 1.9 中的 Profiler 模块以两个尾部下划线命名?

ruby - 哈希火箭被弃用了吗?

ruby-on-rails - NoMethodError:创建用户时未定义方法 'password'

Ruby、数组、对象 - 选择对象

Ruby - 获取哈希值

ruby - 为什么 Ruby 1.9 lambda 调用不可能没有圆括号前面的点?

ruby - ruby 方法查找中的*实际*步骤是什么?

ruby-on-rails - HTTParty 不删除 HTML 特殊字符

ruby - 检查一个散列是否包含另一个散列