class BasicObject
BasicObject is the parent class of all classes in Ruby. In particular,BasicObject is the parent class of classObject, which is itself the default parent class of every Ruby class:
classFoo;endFoo.superclass# => ObjectObject.superclass# => BasicObject
BasicObject is the only class that has no parent:
BasicObject.superclass# => nil
ClassBasicObject can be used to create an object hierarchy (e.g., classDelegator) that is independent of Ruby’s object hierarchy. Such objects:
Do not have namespace “pollution” from the many methods provided in class
Objectand its included moduleKernel.Do not have definitions of common classes, and so references to such common classes must be fully qualified (
::String, notString).
A variety of strategies can be used to provide useful portions of the Standard Library in subclasses ofBasicObject:
The immediate subclass could
include Kernel, which would define methods such asputs,exit, etc.A custom Kernel-like module could be created and included.
Delegation can be used via
method_missing:classMyObjectSystem<BasicObjectDELEGATE = [:puts,:p]defmethod_missing(name,*args,&block)returnsuperunlessDELEGATE.include?name::Kernel.send(name,*args,&block)enddefrespond_to_missing?(name,include_private =false)DELEGATE.include?(name)endend
What’s Here¶↑
These are the methods defined for BasicObject:
::new: Returns a new BasicObject instance.!: Returns the boolean negation ofself:trueorfalse.!=: Returns whetherselfand the given object arenot equal.==: Returns whetherselfand the given object are equivalent.__id__: Returns the integer object identifier forself.__send__: Calls the method identified by the given symbol.equal?: Returns whetherselfand the given object are the same object.instance_eval: Evaluates the given string or block in the context ofself.instance_exec: Executes the given block in the context ofself, passing the given arguments.method_missing: Called whenselfis called with a method it does not define.singleton_method_added: Called when a singleton method is added toself.singleton_method_removed: Called when a singleton method is removed fromself.singleton_method_undefined: Called when a singleton method is undefined inself.
Public Class Methods
Public Instance Methods
Source
VALUErb_obj_not_equal(VALUE obj1, VALUE obj2){ VALUE result = rb_funcall(obj1, id_eq, 1, obj2); return rb_obj_not(result);}Returns true if two objects are not-equal, otherwise false.
Source
VALUErb_obj_equal(VALUE obj1, VALUE obj2){ return RBOOL(obj1 == obj2);}Equality — At theObject level,== returnstrue only ifobj andother are the same object. Typically, this method is overridden in descendant classes to provide class-specific meaning.
Unlike==, theequal? method should never be overridden by subclasses as it is used to determine object identity (that is,a.equal?(b) if and only ifa is the same object asb):
obj ="a"other =obj.dupobj==other#=> trueobj.equal?other#=> falseobj.equal?obj#=> true
The eql? method returnstrue ifobj andother refer to the same hash key. This is used byHash to test members for equality. For any pair of objects where eql? returnstrue, the hash value of both objects must be equal. So any subclass that overrides eql? should also override hash appropriately.
For objects of classObject, eql? is synonymous with==. Subclasses normally continue this tradition by aliasing eql? to their overridden== method, but there are exceptions.Numeric types, for example, perform type conversion across==, but not across eql?, so:
1==1.0#=> true1.eql?1.0#=> false
Source
VALUErb_obj_id(VALUE obj){ /* If obj is an immediate, the object ID is obj directly converted to a Numeric. * Otherwise, the object ID is a Numeric that is a non-zero multiple of * (RUBY_IMMEDIATE_MASK + 1) which guarantees that it does not collide with * any immediates. */ return rb_find_object_id(rb_gc_get_objspace(), obj, object_id);}Returns an integer identifier forobj.
The same number will be returned on all calls toobject_id for a given object, and no two active objects will share an id.
Note: that some objects of builtin classes are reused for optimization. This is the case for immediate values and frozen string literals.
BasicObject implements__id__,Kernel implementsobject_id.
Immediate values are not passed by reference but are passed by value:nil,true,false, Fixnums, Symbols, and some Floats.
Object.new.object_id==Object.new.object_id# => false(21*2).object_id== (21*2).object_id# => true"hello".object_id=="hello".object_id# => false"hi".freeze.object_id=="hi".freeze.object_id# => true
Source
VALUErb_f_send(int argc, VALUE *argv, VALUE recv){ return send_internal_kw(argc, argv, recv, CALL_FCALL);}Invokes the method identified bysymbol, passing it any arguments specified. When the method is identified by a string, the string is converted to a symbol.
BasicObject implements__send__,Kernel implementssend.__send__ is safer thansend whenobj has the same method name likeSocket. See alsopublic_send.
classKlassdefhello(*args)"Hello "+args.join(' ')endendk =Klass.newk.send:hello,"gentle","readers"#=> "Hello gentle readers"
Equality — At theObject level,== returnstrue only ifobj andother are the same object. Typically, this method is overridden in descendant classes to provide class-specific meaning.
Unlike==, theequal? method should never be overridden by subclasses as it is used to determine object identity (that is,a.equal?(b) if and only ifa is the same object asb):
obj ="a"other =obj.dupobj==other#=> trueobj.equal?other#=> falseobj.equal?obj#=> true
The eql? method returnstrue ifobj andother refer to the same hash key. This is used byHash to test members for equality. For any pair of objects where eql? returnstrue, the hash value of both objects must be equal. So any subclass that overrides eql? should also override hash appropriately.
For objects of classObject, eql? is synonymous with==. Subclasses normally continue this tradition by aliasing eql? to their overridden== method, but there are exceptions.Numeric types, for example, perform type conversion across==, but not across eql?, so:
1==1.0#=> true1.eql?1.0#=> false
Source
static VALUErb_obj_instance_eval_internal(int argc, const VALUE *argv, VALUE self){ return specific_eval(argc, argv, self, TRUE, RB_PASS_CALLED_KEYWORDS);}Evaluates a string containing Ruby source code, or the given block, within the context of the receiver (obj). In order to set the context, the variableself is set toobj while the code is executing, giving the code access toobj’s instance variables and private methods.
Wheninstance_eval is given a block,obj is also passed in as the block’s only argument.
Wheninstance_eval is given aString, the optional second and third parameters supply a filename and starting line number that are used when reporting compilation errors.
classKlassWithSecretdefinitialize@secret =99endprivatedefthe_secret"Ssssh! The secret is #{@secret}."endendk =KlassWithSecret.newk.instance_eval {@secret }#=> 99k.instance_eval {the_secret }#=> "Ssssh! The secret is 99."k.instance_eval {|obj|obj==self }#=> true
Source
static VALUErb_obj_instance_exec_internal(int argc, const VALUE *argv, VALUE self){ return yield_under(self, TRUE, argc, argv, RB_PASS_CALLED_KEYWORDS);}Executes the given block within the context of the receiver (obj). In order to set the context, the variableself is set toobj while the code is executing, giving the code access toobj’s instance variables. Arguments are passed as block parameters.
classKlassWithSecretdefinitialize@secret =99endendk =KlassWithSecret.newk.instance_exec(5) {|x|@secret+x }#=> 104
Private Instance Methods
Source
static VALUErb_method_missing(int argc, const VALUE *argv, VALUE obj){ rb_execution_context_t *ec = GET_EC(); raise_method_missing(ec, argc, argv, obj, ec->method_missing_reason); UNREACHABLE_RETURN(Qnil);}Invoked by Ruby whenobj is sent a message it cannot handle.symbol is the symbol for the method called, andargs are any arguments that were passed to it. By default, the interpreter raises an error when this method is called. However, it is possible to override the method to provide more dynamic behavior. If it is decided that a particular method should not be handled, thensuper should be called, so that ancestors can pick up the missing method. The example below creates a classRoman, which responds to methods with names consisting of roman numerals, returning the corresponding integer values.
classRomandefroman_to_int(str)# ...enddefmethod_missing(symbol,*args)str =symbol.id2namebeginroman_to_int(str)rescuesuper(symbol,*args)endendendr =Roman.newr.iv#=> 4r.xxiii#=> 23r.mm#=> 2000r.foo#=> NoMethodError
Source
#define rb_obj_singleton_method_added rb_obj_dummy1
Invoked as a callback whenever a singleton method is added to the receiver.
moduleChattydefChatty.singleton_method_added(id)puts"Adding #{id.id2name}"enddefself.one()enddeftwo()enddefChatty.three()endend
produces:
Addingsingleton_method_addedAddingoneAddingthree
Source
#define rb_obj_singleton_method_removed rb_obj_dummy1
Invoked as a callback whenever a singleton method is removed from the receiver.
moduleChattydefChatty.singleton_method_removed(id)puts"Removing #{id.id2name}"enddefself.one()enddeftwo()enddefChatty.three()endclass<<selfremove_method:threeremove_method:oneendend
produces:
RemovingthreeRemovingone
Source
#define rb_obj_singleton_method_undefined rb_obj_dummy1
Invoked as a callback whenever a singleton method is undefined in the receiver.
moduleChattydefChatty.singleton_method_undefined(id)puts"Undefining #{id.id2name}"enddefChatty.one()endclass<<selfundef_method(:one)endend
produces:
Undefiningone