Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

ruby-1.9

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

like image 471
Sergey Avatar asked Jan 17 '12 12:01

Sergey


People also ask

What is BasicObject in Ruby?

BasicObject is the parent class of all classes in Ruby. It's an explicit blank class. 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.

What is objects in Ruby?

Objects are instances of the class. You will now learn how to create objects of a class in Ruby. You can create objects in Ruby by using the method new of the class. The method new is a unique type of method, which is predefined in the Ruby library. The new method belongs to the class methods.

What is object class in Ruby?

Object is the default root of all Ruby objects. Object inherits from BasicObject which allows creating alternate object hierarchies. Methods on Object are available to all classes unless explicitly overridden. Object mixes in the Kernel module, making the built-in kernel functions globally accessible.

Is everything an object in Ruby?

Practically everything in Ruby is an Object, with the exception of control structures. Whether or not under the covers a method, code block or operator is or isn't an Object, they are represented as Objects and can be thought of as such.


1 Answers

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 
like image 170
Aliaksei Kliuchnikau Avatar answered Oct 10 '22 09:10

Aliaksei Kliuchnikau