What's the difference between Object and BasicObject in Ruby?

只谈情不闲聊 提交于 2019-11-26 23:00:17

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/8894817/whats-the-difference-between-object-and-basicobject-in-ruby

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!