Class: Class
Overview
Classes in Ruby are first-class objects—each is an instance of class Class.
Typically, you create a new class by using:
class Name
# some code describing the class behavior
end
When a new class is created, an object of type Class is initialized and assigned to a global constant (Name in this case).
When Name.new
is called to create a new object, the #new method in Class is run by default. This can be demonstrated by overriding #new in Class:
class Class
alias old_new new
def new(*args)
print "Creating a new ", self.name, "\n"
old_new(*args)
end
end
class Name
end
n = Name.new
produces:
Creating a new Name
Classes, modules, and objects are interrelated. In the diagram that follows, the vertical arrows represent inheritance, and the parentheses metaclasses. All metaclasses are instances of the class ‘Class’.
+---------+ +-...
| | |
BasicObject-----|-->(BasicObject)-------|-...
^ | ^ |
| | | |
Object---------|----->(Object)---------|-...
^ | ^ |
| | | |
+-------+ | +--------+ |
| | | | | |
| Module-|---------|--->(Module)-|-...
| ^ | | ^ |
| | | | | |
| Class-|---------|---->(Class)-|-...
| ^ | | ^ |
| +---+ | +----+
| |
obj--->OtherClass---------->(OtherClass)-----------...
Instance Method Summary collapse
-
#allocate ⇒ Object
Allocates space for a new object of class’s class and does not call initialize on the new instance.
-
#attached_object ⇒ Object
Returns the object for which the receiver is the singleton class.
-
#inherited ⇒ Object
private
call-seq: inherited(subclass).
-
#initialize(*args) ⇒ Object
constructor
Creates a new anonymous (unnamed) class with the given superclass (or Object if no parameter is given).
-
#new(args, ...) ⇒ Object
Calls #allocate to create a new object of class’s class, then invokes that object’s #initialize method, passing it args.
-
#subclasses ⇒ Array
Returns an array of classes where the receiver is the direct superclass of the class, excluding singleton classes.
-
#superclass ⇒ nil
Returns the superclass of class, or
nil
.
Methods inherited from Module
#<, #<=, #<=>, #==, #===, #>, #>=, #alias_method, #ancestors, #append_features, #attr, #attr_accessor, #attr_reader, #attr_writer, #autoload, #autoload?, #class_eval, #class_exec, #class_variable_defined?, #class_variable_get, #class_variable_set, #class_variables, #const_added, #const_defined?, #const_get, #const_missing, #const_set, #const_source_location, #constants, constants, #define_method, #deprecate_constant, #extend_object, #extended, #freeze, #include, #include?, #included, #included_modules, #initialize_clone, #initialize_copy, #instance_method, #instance_methods, #method_added, #method_defined?, #method_removed, #method_undefined, #module_eval, #module_exec, #module_function, #name, nesting, #prepend, #prepend_features, #prepended, #private, #private_class_method, #private_constant, #private_instance_methods, #private_method_defined?, #protected, #protected_instance_methods, #protected_method_defined?, #public, #public_class_method, #public_constant, #public_instance_method, #public_instance_methods, #public_method_defined?, #refine, #refinements, #remove_class_variable, #remove_const, #remove_method, #ruby2_keywords, #set_temporary_name, #singleton_class?, #to_s, #undef_method, #undefined_instance_methods, used_modules, used_refinements, #using
Constructor Details
#new(super_class = Object) ⇒ Class #new(super_class = Object) {|mod| ... } ⇒ Class
Creates a new anonymous (unnamed) class with the given superclass (or Object if no parameter is given). You can give a class a name by assigning the class object to a constant.
If a block is given, it is passed the class object, and the block is evaluated in the context of this class like #class_eval.
fred = Class.new do
def meth1
"hello"
end
def meth2
"bye"
end
end
a = fred.new #=> #<#<Class:0x100381890>:0x100376b98>
a.meth1 #=> "hello"
a.meth2 #=> "bye"
Assign the class to a constant (name starting uppercase) if you want to treat it like a regular class.
2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 |
# File 'object.c', line 2006 static VALUE rb_class_initialize(int argc, VALUE *argv, VALUE klass) { VALUE super; if (RCLASS_SUPER(klass) != 0 || klass == rb_cBasicObject) { rb_raise(rb_eTypeError, "already initialized class"); } if (rb_check_arity(argc, 0, 1) == 0) { super = rb_cObject; } else { super = argv[0]; rb_check_inheritable(super); if (super != rb_cBasicObject && !RCLASS_SUPER(super)) { rb_raise(rb_eTypeError, "can't inherit uninitialized class"); } } RCLASS_SET_SUPER(klass, super); (klass, RBASIC(super)->klass); rb_class_inherited(super, klass); rb_mod_initialize_exec(klass); return klass; } |
Instance Method Details
#allocate ⇒ Object
Allocates space for a new object of class’s class and does not call initialize on the new instance. The returned object must be an instance of class.
klass = Class.new do
def initialize(*args)
@initialized = true
end
def initialized?
@initialized || false
end
end
klass.allocate.initialized? #=> false
2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 |
# File 'object.c', line 2065 static VALUE rb_class_alloc_m(VALUE klass) { rb_alloc_func_t allocator = class_get_alloc_func(klass); if (!rb_obj_respond_to(klass, rb_intern("allocate"), 1)) { rb_raise(rb_eTypeError, "calling %"PRIsVALUE".allocate is prohibited", klass); } return class_call_alloc_func(allocator, klass); } |
#attached_object ⇒ Object
Returns the object for which the receiver is the singleton class.
Raises an TypeError if the class is not a singleton class.
class Foo; end
Foo.singleton_class.attached_object #=> Foo
Foo.attached_object #=> TypeError: `Foo' is not a singleton class
Foo.new.singleton_class.attached_object #=> #<Foo:0x000000010491a370>
TrueClass.attached_object #=> TypeError: `TrueClass' is not a singleton class
NilClass.attached_object #=> TypeError: `NilClass' is not a singleton class
1706 1707 1708 1709 1710 1711 1712 1713 1714 |
# File 'class.c', line 1706 VALUE rb_class_attached_object(VALUE klass) { if (!FL_TEST(klass, FL_SINGLETON)) { rb_raise(rb_eTypeError, "`%"PRIsVALUE"' is not a singleton class", klass); } return RCLASS_ATTACHED_OBJECT(klass); } |
#inherited ⇒ Object (private)
call-seq:
inherited(subclass)
Callback invoked whenever a subclass of the current class is created.
Example:
class Foo
def self.inherited(subclass)
puts "New subclass: #{subclass}"
end
end
class Bar < Foo
end
class Baz < Bar
end
produces:
New subclass: Bar
New subclass: Baz
#new(args, ...) ⇒ Object
Calls #allocate to create a new object of class’s class, then invokes that object’s #initialize method, passing it args. This is the method that ends up getting called whenever an object is constructed using .new
.
2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 |
# File 'object.c', line 2134 VALUE rb_class_new_instance_pass_kw(int argc, const VALUE *argv, VALUE klass) { VALUE obj; obj = rb_class_alloc(klass); rb_obj_call_init_kw(obj, argc, argv, RB_PASS_CALLED_KEYWORDS); return obj; } |
#subclasses ⇒ Array
Returns an array of classes where the receiver is the direct superclass of the class, excluding singleton classes. The order of the returned array is not defined.
class A; end
class B < A; end
class C < B; end
class D < A; end
A.subclasses #=> [D, B]
B.subclasses #=> [C]
C.subclasses #=> []
Anonymous subclasses (not associated with a constant) are returned, too:
c = Class.new(A)
A.subclasses # => [#<Class:0x00007f003c77bd78>, D, B]
Note that the parent does not hold references to subclasses and doesn’t prevent them from being garbage collected. This means that the subclass might disappear when all references to it are dropped:
# drop the reference to subclass, it can be garbage-collected now
c = nil
A.subclasses
# It can be
# => [#<Class:0x00007f003c77bd78>, D, B]
# ...or just
# => [D, B]
# ...depending on whether garbage collector was run
1683 1684 1685 1686 1687 |
# File 'class.c', line 1683 VALUE rb_class_subclasses(VALUE klass) { return class_descendants(klass, true); } |
#superclass ⇒ nil
Returns the superclass of class, or nil
.
File.superclass #=> IO
IO.superclass #=> Object
Object.superclass #=> BasicObject
class Foo; end
class Bar < Foo; end
Bar.superclass #=> Foo
Returns nil when the given class does not have a parent class:
BasicObject.superclass #=> nil
2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 |
# File 'object.c', line 2190 VALUE rb_class_superclass(VALUE klass) { RUBY_ASSERT(RB_TYPE_P(klass, T_CLASS)); VALUE super = RCLASS_SUPER(klass); if (!super) { if (klass == rb_cBasicObject) return Qnil; rb_raise(rb_eTypeError, "uninitialized class"); } if (!RCLASS_SUPERCLASS_DEPTH(klass)) { return Qnil; } else { super = RCLASS_SUPERCLASSES(klass)[RCLASS_SUPERCLASS_DEPTH(klass) - 1]; RUBY_ASSERT(RB_TYPE_P(klass, T_CLASS)); return super; } } |