这些类之间有什么区别?他们的目的有什么区别?
最佳答案
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/