Class | Module |
In: |
object.c
|
A Module is a collection of methods and constants. The methods in a module may be instance methods or module methods. Instance methods appear as methods in a class when the module is included, module methods do not. Conversely, module methods may be called without creating an encapsulating object, while instance methods may not. (See Module#module_function)
In the descriptions that follow, the parameter syml refers to a symbol, which is either a quoted string or a Symbol (such as :name).
module Mod include Math CONST = 1 def meth # ... end end Mod.class #=> Module Mod.constants #=> ["E", "PI", "CONST"] Mod.instance_methods #=> ["meth"]
Returns an array of the names of all constants defined in the system. This list includes the names of all modules and classes.
p Module.constants.sort[1..5]
produces:
["ARGV", "ArgumentError", "Array", "Bignum", "Binding"]
/* * call-seq: * Module.constants => array * * Returns an array of the names of all constants defined in the * system. This list includes the names of all modules and classes. * * p Module.constants.sort[1..5] * * <em>produces:</em> * * ["ARGV", "ArgumentError", "Array", "Bignum", "Binding"] */ static VALUE rb_mod_s_constants() { NODE *cbase = ruby_cref; void *data = 0; while (cbase) { if (!NIL_P(cbase->nd_clss)) { data = rb_mod_const_at(cbase->nd_clss, data); } cbase = cbase->nd_next; } if (!NIL_P(ruby_cbase)) { data = rb_mod_const_of(ruby_cbase, data); } return rb_const_list(data); }
Returns the list of Modules nested at the point of call.
module M1 module M2 $a = Module.nesting end end $a #=> [M1::M2, M1] $a[0].name #=> "M1::M2"
/* * call-seq: * Module.nesting => array * * Returns the list of +Modules+ nested at the point of call. * * module M1 * module M2 * $a = Module.nesting * end * end * $a #=> [M1::M2, M1] * $a[0].name #=> "M1::M2" */ static VALUE rb_mod_nesting() { NODE *cbase = ruby_cref; VALUE ary = rb_ary_new(); while (cbase && cbase->nd_next) { if (!NIL_P(cbase->nd_clss)) rb_ary_push(ary, cbase->nd_clss); cbase = cbase->nd_next; } if (ruby_wrapper && RARRAY(ary)->len == 0) { rb_ary_push(ary, ruby_wrapper); } return ary; }
Creates a new anonymous module. If a block is given, it is passed the module object, and the block is evaluated in the context of this module using module_eval.
Fred = Module.new do def meth1 "hello" end def meth2 "bye" end end a = "my string" a.extend(Fred) #=> "my string" a.meth1 #=> "hello" a.meth2 #=> "bye"
/* * call-seq: * Module.new => mod * Module.new {|mod| block } => mod * * Creates a new anonymous module. If a block is given, it is passed * the module object, and the block is evaluated in the context of this * module using <code>module_eval</code>. * * Fred = Module.new do * def meth1 * "hello" * end * def meth2 * "bye" * end * end * a = "my string" * a.extend(Fred) #=> "my string" * a.meth1 #=> "hello" * a.meth2 #=> "bye" */ static VALUE rb_mod_initialize(module) VALUE module; { if (rb_block_given_p()) { rb_mod_module_eval(0, 0, module); } return Qnil; }
Returns true if mod is a subclass of other. Returns nil if there‘s no relationship between the two. (Think of the relationship in terms of the class definition: "class A<B" implies "A<B").
/* * call-seq: * mod < other => true, false, or nil * * Returns true if <i>mod</i> is a subclass of <i>other</i>. Returns * <code>nil</code> if there's no relationship between the two. * (Think of the relationship in terms of the class definition: * "class A<B" implies "A<B"). * */ static VALUE rb_mod_lt(mod, arg) VALUE mod, arg; { if (mod == arg) return Qfalse; return rb_class_inherited_p(mod, arg); }
Returns true if mod is a subclass of other or is the same as other. Returns nil if there‘s no relationship between the two. (Think of the relationship in terms of the class definition: "class A<B" implies "A<B").
/* * call-seq: * mod <= other => true, false, or nil * * Returns true if <i>mod</i> is a subclass of <i>other</i> or * is the same as <i>other</i>. Returns * <code>nil</code> if there's no relationship between the two. * (Think of the relationship in terms of the class definition: * "class A<B" implies "A<B"). * */ VALUE rb_class_inherited_p(mod, arg) VALUE mod, arg; { VALUE start = mod; if (mod == arg) return Qtrue; switch (TYPE(arg)) { case T_MODULE: case T_CLASS: break; default: rb_raise(rb_eTypeError, "compared with non class/module"); } if (FL_TEST(mod, FL_SINGLETON)) { if (RCLASS(mod)->m_tbl == RCLASS(arg)->m_tbl) return Qtrue; mod = RBASIC(mod)->klass; } while (mod) { if (RCLASS(mod)->m_tbl == RCLASS(arg)->m_tbl) return Qtrue; mod = RCLASS(mod)->super; } /* not mod < arg; check if mod > arg */ while (arg) { if (RCLASS(arg)->m_tbl == RCLASS(start)->m_tbl) return Qfalse; arg = RCLASS(arg)->super; } return Qnil; }
Comparison—Returns -1 if mod includes other_mod, 0 if mod is the same as other_mod, and +1 if mod is included by other_mod or if mod has no relationship with other_mod. Returns nil if other_mod is not a module.
/* * call-seq: * mod <=> other_mod => -1, 0, +1, or nil * * Comparison---Returns -1 if <i>mod</i> includes <i>other_mod</i>, 0 if * <i>mod</i> is the same as <i>other_mod</i>, and +1 if <i>mod</i> is * included by <i>other_mod</i> or if <i>mod</i> has no relationship with * <i>other_mod</i>. Returns <code>nil</code> if <i>other_mod</i> is * not a module. */ static VALUE rb_mod_cmp(mod, arg) VALUE mod, arg; { VALUE cmp; if (mod == arg) return INT2FIX(0); switch (TYPE(arg)) { case T_MODULE: case T_CLASS: break; default: return Qnil; } cmp = rb_class_inherited_p(mod, arg); if (NIL_P(cmp)) return Qnil; if (cmp) { return INT2FIX(-1); } return INT2FIX(1); }
Equality—At the Object level, == returns true only if obj and other are the same object. Typically, this method is overridden in descendent classes to provide class-specific meaning.
Unlike ==, the equal? method should never be overridden by subclasses: it is used to determine object identity (that is, a.equal?(b) iff a is the same object as b).
The eql? method returns true if obj and anObject have the same value. Used by Hash to test members for equality. For objects of class Object, eql? is synonymous with ==. Subclasses normally continue this tradition, but there are exceptions. Numeric types, for example, perform type conversion across ==, but not across eql?, so:
1 == 1.0 #=> true 1.eql? 1.0 #=> false
/* * call-seq: * obj == other => true or false * obj.equal?(other) => true or false * obj.eql?(other) => true or false * * Equality---At the <code>Object</code> level, <code>==</code> returns * <code>true</code> only if <i>obj</i> and <i>other</i> are the * same object. Typically, this method is overridden in descendent * classes to provide class-specific meaning. * * Unlike <code>==</code>, the <code>equal?</code> method should never be * overridden by subclasses: it is used to determine object identity * (that is, <code>a.equal?(b)</code> iff <code>a</code> is the same * object as <code>b</code>). * * The <code>eql?</code> method returns <code>true</code> if <i>obj</i> and <i>anObject</i> have the * same value. Used by <code>Hash</code> to test members for equality. * For objects of class <code>Object</code>, <code>eql?</code> is * synonymous with <code>==</code>. Subclasses normally continue this * tradition, but there are exceptions. <code>Numeric</code> types, for * example, perform type conversion across <code>==</code>, but not * across <code>eql?</code>, so: * * 1 == 1.0 #=> true * 1.eql? 1.0 #=> false */ static VALUE rb_obj_equal(obj1, obj2) VALUE obj1, obj2; { if (obj1 == obj2) return Qtrue; return Qfalse; }
Case Equality—Returns true if anObject is an instance of mod or one of mod‘s descendents. Of limited use for modules, but can be used in case statements to classify objects by class.
/* * call-seq: * mod === obj => true or false * * Case Equality---Returns <code>true</code> if <i>anObject</i> is an * instance of <i>mod</i> or one of <i>mod</i>'s descendents. Of * limited use for modules, but can be used in <code>case</code> * statements to classify objects by class. */ static VALUE rb_mod_eqq(mod, arg) VALUE mod, arg; { return rb_obj_is_kind_of(arg, mod); }
Returns true if mod is an ancestor of other. Returns nil if there‘s no relationship between the two. (Think of the relationship in terms of the class definition: "class A<B" implies "B>A").
/* * call-seq: * mod > other => true, false, or nil * * Returns true if <i>mod</i> is an ancestor of <i>other</i>. Returns * <code>nil</code> if there's no relationship between the two. * (Think of the relationship in terms of the class definition: * "class A<B" implies "B>A"). * */ static VALUE rb_mod_gt(mod, arg) VALUE mod, arg; { if (mod == arg) return Qfalse; return rb_mod_ge(mod, arg); }
Returns true if mod is an ancestor of other, or the two modules are the same. Returns nil if there‘s no relationship between the two. (Think of the relationship in terms of the class definition: "class A<B" implies "B>A").
/* * call-seq: * mod >= other => true, false, or nil * * Returns true if <i>mod</i> is an ancestor of <i>other</i>, or the * two modules are the same. Returns * <code>nil</code> if there's no relationship between the two. * (Think of the relationship in terms of the class definition: * "class A<B" implies "B>A"). * */ static VALUE rb_mod_ge(mod, arg) VALUE mod, arg; { switch (TYPE(arg)) { case T_MODULE: case T_CLASS: break; default: rb_raise(rb_eTypeError, "compared with non class/module"); } return rb_class_inherited_p(arg, mod); }
Makes new_name a new copy of the method old_name. This can be used to retain access to methods that are overridden.
module Mod alias_method :orig_exit, :exit def exit(code=0) puts "Exiting with code #{code}" orig_exit(code) end end include Mod exit(99)
produces:
Exiting with code 99
/* * call-seq: * alias_method(new_name, old_name) => self * * Makes <i>new_name</i> a new copy of the method <i>old_name</i>. This can * be used to retain access to methods that are overridden. * * module Mod * alias_method :orig_exit, :exit * def exit(code=0) * puts "Exiting with code #{code}" * orig_exit(code) * end * end * include Mod * exit(99) * * <em>produces:</em> * * Exiting with code 99 */ static VALUE rb_mod_alias_method(mod, newname, oldname) VALUE mod, newname, oldname; { rb_alias(mod, rb_to_id(newname), rb_to_id(oldname)); return mod; }
Returns a list of modules included in mod (including mod itself).
module Mod include Math include Comparable end Mod.ancestors #=> [Mod, Comparable, Math] Math.ancestors #=> [Math]
/* * call-seq: * mod.ancestors -> array * * Returns a list of modules included in <i>mod</i> (including * <i>mod</i> itself). * * module Mod * include Math * include Comparable * end * * Mod.ancestors #=> [Mod, Comparable, Math] * Math.ancestors #=> [Math] */ VALUE rb_mod_ancestors(mod) VALUE mod; { VALUE p, ary = rb_ary_new(); for (p = mod; p; p = RCLASS(p)->super) { if (FL_TEST(p, FL_SINGLETON)) continue; if (BUILTIN_TYPE(p) == T_ICLASS) { rb_ary_push(ary, RBASIC(p)->klass); } else { rb_ary_push(ary, p); } } return ary; }
When this module is included in another, Ruby calls append_features in this module, passing it the receiving module in mod. Ruby‘s default implementation is to add the constants, methods, and module variables of this module to mod if this module has not already been added to mod or one of its ancestors. See also Module#include.
/* * call-seq: * append_features(mod) => mod * * When this module is included in another, Ruby calls * <code>append_features</code> in this module, passing it the * receiving module in _mod_. Ruby's default implementation is * to add the constants, methods, and module variables of this module * to _mod_ if this module has not already been added to * _mod_ or one of its ancestors. See also <code>Module#include</code>. */ static VALUE rb_mod_append_features(module, include) VALUE module, include; { switch (TYPE(include)) { case T_CLASS: case T_MODULE: break; default: Check_Type(include, T_CLASS); break; } rb_include_module(include, module); return module; }
Defines a named attribute for this module, where the name is symbol.id2name, creating an instance variable (@name) and a corresponding access method to read it. If the optional writable argument is true, also creates a method called name= to set the attribute.
module Mod attr :size, true end
is equivalent to:
module Mod def size @size end def size=(val) @size = val end end
/* * call-seq: * attr(symbol, writable=false) => nil * * Defines a named attribute for this module, where the name is * <i>symbol.</i><code>id2name</code>, creating an instance variable * (<code>@name</code>) and a corresponding access method to read it. * If the optional <i>writable</i> argument is <code>true</code>, also * creates a method called <code>name=</code> to set the attribute. * * module Mod * attr :size, true * end * * <em>is equivalent to:</em> * * module Mod * def size * @size * end * def size=(val) * @size = val * end * end */ static VALUE rb_mod_attr(argc, argv, klass) int argc; VALUE *argv; VALUE klass; { VALUE name, pub; rb_scan_args(argc, argv, "11", &name, &pub); rb_attr(klass, rb_to_id(name), 1, RTEST(pub), Qtrue); return Qnil; }
Equivalent to calling ``attrsymbol, true’’ on each symbol in turn.
module Mod attr_accessor(:one, :two) end Mod.instance_methods.sort #=> ["one", "one=", "two", "two="]
/* * call-seq: * attr_accessor(symbol, ...) => nil * * Equivalent to calling ``<code>attr</code><i>symbol</i><code>, * true</code>'' on each <i>symbol</i> in turn. * * module Mod * attr_accessor(:one, :two) * end * Mod.instance_methods.sort #=> ["one", "one=", "two", "two="] */ static VALUE rb_mod_attr_accessor(argc, argv, klass) int argc; VALUE *argv; VALUE klass; { int i; for (i=0; i<argc; i++) { rb_attr(klass, rb_to_id(argv[i]), 1, 1, Qtrue); } return Qnil; }
Creates instance variables and corresponding methods that return the value of each instance variable. Equivalent to calling ``attr:name’’ on each name in turn.
/* * call-seq: * attr_reader(symbol, ...) => nil * * Creates instance variables and corresponding methods that return the * value of each instance variable. Equivalent to calling * ``<code>attr</code><i>:name</i>'' on each name in turn. */ static VALUE rb_mod_attr_reader(argc, argv, klass) int argc; VALUE *argv; VALUE klass; { int i; for (i=0; i<argc; i++) { rb_attr(klass, rb_to_id(argv[i]), 1, 0, Qtrue); } return Qnil; }
Creates an accessor method to allow assignment to the attribute aSymbol.id2name.
/* * call-seq: * attr_writer(symbol, ...) => nil * * Creates an accessor method to allow assignment to the attribute * <i>aSymbol</i><code>.id2name</code>. */ static VALUE rb_mod_attr_writer(argc, argv, klass) int argc; VALUE *argv; VALUE klass; { int i; for (i=0; i<argc; i++) { rb_attr(klass, rb_to_id(argv[i]), 0, 1, Qtrue); } return Qnil; }
Registers filename to be loaded (using Kernel::require) the first time that name (which may be a String or a symbol) is accessed in the namespace of mod.
module A end A.autoload(:B, "b") A::B.doit # autoloads "b"
/* * call-seq: * mod.autoload(name, filename) => nil * * Registers _filename_ to be loaded (using <code>Kernel::require</code>) * the first time that _name_ (which may be a <code>String</code> or * a symbol) is accessed in the namespace of _mod_. * * module A * end * A.autoload(:B, "b") * A::B.doit # autoloads "b" */ static VALUE rb_mod_autoload(mod, sym, file) VALUE mod; VALUE sym; VALUE file; { ID id = rb_to_id(sym); Check_SafeStr(file); rb_autoload(mod, id, RSTRING(file)->ptr); return Qnil; }
Returns filename to be loaded if name is registered as autoload in the namespace of mod.
module A end A.autoload(:B, "b") A.autoload?(:B) # => "b"
/* * call-seq: * mod.autoload?(name) => String or nil * * Returns _filename_ to be loaded if _name_ is registered as * +autoload+ in the namespace of _mod_. * * module A * end * A.autoload(:B, "b") * A.autoload?(:B) # => "b" */ static VALUE rb_mod_autoload_p(mod, sym) VALUE mod, sym; { return rb_autoload_p(mod, rb_to_id(sym)); }
Evaluates the string or block in the context of mod. This can be used to add methods to a class. module_eval returns the result of evaluating its argument. The optional filename and lineno parameters set the text for error messages.
class Thing end a = %q{def hello() "Hello there!" end} Thing.module_eval(a) puts Thing.new.hello() Thing.module_eval("invalid code", "dummy", 123)
produces:
Hello there! dummy:123:in `module_eval': undefined local variable or method `code' for Thing:Class
/* * call-seq: * mod.class_eval(string [, filename [, lineno]]) => obj * mod.module_eval {|| block } => obj * * Evaluates the string or block in the context of _mod_. This can * be used to add methods to a class. <code>module_eval</code> returns * the result of evaluating its argument. The optional _filename_ * and _lineno_ parameters set the text for error messages. * * class Thing * end * a = %q{def hello() "Hello there!" end} * Thing.module_eval(a) * puts Thing.new.hello() * Thing.module_eval("invalid code", "dummy", 123) * * <em>produces:</em> * * Hello there! * dummy:123:in `module_eval': undefined local variable * or method `code' for Thing:Class */ VALUE rb_mod_module_eval(argc, argv, mod) int argc; VALUE *argv; VALUE mod; { return specific_eval(argc, argv, mod, mod); }
Evaluates the given block in the context of the class/module. The method defined in the block will belong to the receiver.
class Thing end Thing.class_exec{ def hello() "Hello there!" end } puts Thing.new.hello()
produces:
Hello there!
/* * call-seq: * mod.module_exec(arg...) {|var...| block } => obj * mod.class_exec(arg...) {|var...| block } => obj * * Evaluates the given block in the context of the class/module. * The method defined in the block will belong to the receiver. * * class Thing * end * Thing.class_exec{ * def hello() "Hello there!" end * } * puts Thing.new.hello() * * <em>produces:</em> * * Hello there! */ VALUE rb_mod_module_exec(argc, argv, mod) int argc; VALUE *argv; VALUE mod; { return yield_under(mod, mod, rb_ary_new4(argc, argv)); }
Returns true if the given class variable is defined in obj.
class Fred @@foo = 99 end Fred.class_variable_defined?(:@@foo) #=> true Fred.class_variable_defined?(:@@bar) #=> false
/* * call-seq: * obj.class_variable_defined?(symbol) => true or false * * Returns <code>true</code> if the given class variable is defined * in <i>obj</i>. * * class Fred * @@foo = 99 * end * Fred.class_variable_defined?(:@@foo) #=> true * Fred.class_variable_defined?(:@@bar) #=> false */ static VALUE rb_mod_cvar_defined(obj, iv) VALUE obj, iv; { ID id = rb_to_id(iv); if (!rb_is_class_id(id)) { rb_name_error(id, "`%s' is not allowed as a class variable name", rb_id2name(id)); } return rb_cvar_defined(obj, id); }
Returns the value of the given class variable (or throws a NameError exception). The @@ part of the variable name should be included for regular class variables
class Fred @@foo = 99 end def Fred.foo class_variable_get(:@@foo) #=> 99 end
/* * call-seq: * mod.class_variable_get(symbol) => obj * * Returns the value of the given class variable (or throws a * <code>NameError</code> exception). The <code>@@</code> part of the * variable name should be included for regular class variables * * class Fred * @@foo = 99 * end * * def Fred.foo * class_variable_get(:@@foo) #=> 99 * end */ static VALUE rb_mod_cvar_get(obj, iv) VALUE obj, iv; { ID id = rb_to_id(iv); if (!rb_is_class_id(id)) { rb_name_error(id, "`%s' is not allowed as a class variable name", rb_id2name(id)); } return rb_cvar_get(obj, id); }
Sets the class variable names by symbol to object.
class Fred @@foo = 99 def foo @@foo end end def Fred.foo class_variable_set(:@@foo, 101) #=> 101 end Fred.foo Fred.new.foo #=> 101
/* * call-seq: * obj.class_variable_set(symbol, obj) => obj * * Sets the class variable names by <i>symbol</i> to * <i>object</i>. * * class Fred * @@foo = 99 * def foo * @@foo * end * end * * def Fred.foo * class_variable_set(:@@foo, 101) #=> 101 * end * Fred.foo * Fred.new.foo #=> 101 */ static VALUE rb_mod_cvar_set(obj, iv, val) VALUE obj, iv, val; { ID id = rb_to_id(iv); if (!rb_is_class_id(id)) { rb_name_error(id, "`%s' is not allowed as a class variable name", rb_id2name(id)); } rb_cvar_set(obj, id, val, Qfalse); return val; }
Returns an array of the names of class variables in mod and the ancestors of mod.
class One @@var1 = 1 end class Two < One @@var2 = 2 end One.class_variables #=> ["@@var1"] Two.class_variables #=> ["@@var2", "@@var1"]
/* * call-seq: * mod.class_variables => array * * Returns an array of the names of class variables in <i>mod</i> and * the ancestors of <i>mod</i>. * * class One * @@var1 = 1 * end * class Two < One * @@var2 = 2 * end * One.class_variables #=> ["@@var1"] * Two.class_variables #=> ["@@var2", "@@var1"] */ VALUE rb_mod_class_variables(obj) VALUE obj; { VALUE ary = rb_ary_new(); for (;;) { if (RCLASS(obj)->iv_tbl) { st_foreach_safe(RCLASS(obj)->iv_tbl, cv_i, ary); } obj = RCLASS(obj)->super; if (!obj) break; } return ary; }
Returns true if a constant with the given name is defined by mod.
Math.const_defined? "PI" #=> true
/* * call-seq: * mod.const_defined?(sym) => true or false * * Returns <code>true</code> if a constant with the given name is * defined by <i>mod</i>. * * Math.const_defined? "PI" #=> true */ static VALUE rb_mod_const_defined(mod, name) VALUE mod, name; { ID id = rb_to_id(name); if (!rb_is_const_id(id)) { rb_name_error(id, "wrong constant name %s", rb_id2name(id)); } return rb_const_defined_at(mod, id); }
Returns the value of the named constant in mod.
Math.const_get(:PI) #=> 3.14159265358979
/* * call-seq: * mod.const_get(sym) => obj * * Returns the value of the named constant in <i>mod</i>. * * Math.const_get(:PI) #=> 3.14159265358979 */ static VALUE rb_mod_const_get(mod, name) VALUE mod, name; { ID id = rb_to_id(name); if (!rb_is_const_id(id)) { rb_name_error(id, "wrong constant name %s", rb_id2name(id)); } return rb_const_get(mod, id); }
Invoked when a reference is made to an undefined constant in mod. It is passed a symbol for the undefined constant, and returns a value to be used for that constant. The following code is a (very bad) example: if reference is made to an undefined constant, it attempts to load a file whose name is the lowercase version of the constant (thus class Fred is assumed to be in file fred.rb). If found, it returns the value of the loaded class. It therefore implements a perverse kind of autoload facility.
def Object.const_missing(name) @looked_for ||= {} str_name = name.to_s raise "Class not found: #{name}" if @looked_for[str_name] @looked_for[str_name] = 1 file = str_name.downcase require file klass = const_get(name) return klass if klass raise "Class not found: #{name}" end
/* * call-seq: * mod.const_missing(sym) => obj * * Invoked when a reference is made to an undefined constant in * <i>mod</i>. It is passed a symbol for the undefined constant, and * returns a value to be used for that constant. The * following code is a (very bad) example: if reference is made to * an undefined constant, it attempts to load a file whose name is * the lowercase version of the constant (thus class <code>Fred</code> is * assumed to be in file <code>fred.rb</code>). If found, it returns the * value of the loaded class. It therefore implements a perverse * kind of autoload facility. * * def Object.const_missing(name) * @looked_for ||= {} * str_name = name.to_s * raise "Class not found: #{name}" if @looked_for[str_name] * @looked_for[str_name] = 1 * file = str_name.downcase * require file * klass = const_get(name) * return klass if klass * raise "Class not found: #{name}" * end * */ VALUE rb_mod_const_missing(klass, name) VALUE klass, name; { ruby_frame = ruby_frame->prev; /* pop frame for "const_missing" */ uninitialized_constant(klass, rb_to_id(name)); return Qnil; /* not reached */ }
Sets the named constant to the given object, returning that object. Creates a new constant if no constant with the given name previously existed.
Math.const_set("HIGH_SCHOOL_PI", 22.0/7.0) #=> 3.14285714285714 Math::HIGH_SCHOOL_PI - Math::PI #=> 0.00126448926734968
/* * call-seq: * mod.const_set(sym, obj) => obj * * Sets the named constant to the given object, returning that object. * Creates a new constant if no constant with the given name previously * existed. * * Math.const_set("HIGH_SCHOOL_PI", 22.0/7.0) #=> 3.14285714285714 * Math::HIGH_SCHOOL_PI - Math::PI #=> 0.00126448926734968 */ static VALUE rb_mod_const_set(mod, name, value) VALUE mod, name, value; { ID id = rb_to_id(name); if (!rb_is_const_id(id)) { rb_name_error(id, "wrong constant name %s", rb_id2name(id)); } rb_const_set(mod, id, value); return value; }
Returns an array of the names of the constants accessible in mod. This includes the names of constants in any included modules (example at start of section).
/* * call-seq: * mod.constants => array * * Returns an array of the names of the constants accessible in * <i>mod</i>. This includes the names of constants in any included * modules (example at start of section). */ VALUE rb_mod_constants(mod) VALUE mod; { return rb_const_list(rb_mod_const_of(mod, 0)); }
Defines an instance method in the receiver. The method parameter can be a Proc or Method object. If a block is specified, it is used as the method body. This block is evaluated using instance_eval, a point that is tricky to demonstrate because define_method is private. (This is why we resort to the send hack in this example.)
class A def fred puts "In Fred" end def create_method(name, &block) self.class.send(:define_method, name, &block) end define_method(:wilma) { puts "Charge it!" } end class B < A define_method(:barney, instance_method(:fred)) end a = B.new a.barney a.wilma a.create_method(:betty) { p self } a.betty
produces:
In Fred Charge it! #<B:0x401b39e8>
/* * call-seq: * define_method(symbol, method) => new_method * define_method(symbol) { block } => proc * * Defines an instance method in the receiver. The _method_ * parameter can be a +Proc+ or +Method+ object. * If a block is specified, it is used as the method body. This block * is evaluated using <code>instance_eval</code>, a point that is * tricky to demonstrate because <code>define_method</code> is private. * (This is why we resort to the +send+ hack in this example.) * * class A * def fred * puts "In Fred" * end * def create_method(name, &block) * self.class.send(:define_method, name, &block) * end * define_method(:wilma) { puts "Charge it!" } * end * class B < A * define_method(:barney, instance_method(:fred)) * end * a = B.new * a.barney * a.wilma * a.create_method(:betty) { p self } * a.betty * * <em>produces:</em> * * In Fred * Charge it! * #<B:0x401b39e8> */ static VALUE rb_mod_define_method(argc, argv, mod) int argc; VALUE *argv; VALUE mod; { ID id; VALUE body; NODE *node; int noex; if (argc == 1) { id = rb_to_id(argv[0]); body = proc_lambda(); } else if (argc == 2) { id = rb_to_id(argv[0]); body = argv[1]; if (!rb_obj_is_method(body) && !rb_obj_is_proc(body)) { rb_raise(rb_eTypeError, "wrong argument type %s (expected Proc/Method)", rb_obj_classname(body)); } } else { rb_raise(rb_eArgError, "wrong number of arguments (%d for 1)", argc); } if (RDATA(body)->dmark == (RUBY_DATA_FUNC)bm_mark) { node = NEW_DMETHOD(method_unbind(body)); } else if (RDATA(body)->dmark == (RUBY_DATA_FUNC)blk_mark) { struct BLOCK *block; body = proc_clone(body); Data_Get_Struct(body, struct BLOCK, block); block->frame.last_func = id; block->frame.orig_func = id; block->frame.last_class = mod; node = NEW_BMETHOD(body); } else { /* type error */ rb_raise(rb_eTypeError, "wrong argument type (expected Proc/Method)"); } noex = NOEX_PUBLIC; if (ruby_cbase == mod) { if (SCOPE_TEST(SCOPE_PRIVATE)) { noex = NOEX_PRIVATE; } else if (SCOPE_TEST(SCOPE_PROTECTED)) { noex = NOEX_PROTECTED; } } rb_add_method(mod, id, node, noex); return body; }
Extends the specified object by adding this module‘s constants and methods (which are added as singleton methods). This is the callback method used by Object#extend.
module Picky def Picky.extend_object(o) if String === o puts "Can't add Picky to a String" else puts "Picky added to #{o.class}" super end end end (s = Array.new).extend Picky # Call Object.extend (s = "quick brown fox").extend Picky
produces:
Picky added to Array Can't add Picky to a String
/* * call-seq: * extend_object(obj) => obj * * Extends the specified object by adding this module's constants and * methods (which are added as singleton methods). This is the callback * method used by <code>Object#extend</code>. * * module Picky * def Picky.extend_object(o) * if String === o * puts "Can't add Picky to a String" * else * puts "Picky added to #{o.class}" * super * end * end * end * (s = Array.new).extend Picky # Call Object.extend * (s = "quick brown fox").extend Picky * * <em>produces:</em> * * Picky added to Array * Can't add Picky to a String */ static VALUE rb_mod_extend_object(mod, obj) VALUE mod, obj; { rb_extend_object(obj, mod); return obj; }
Prevents further modifications to mod.
/* * call-seq: * mod.freeze * * Prevents further modifications to <i>mod</i>. */ static VALUE rb_mod_freeze(mod) VALUE mod; { rb_mod_to_s(mod); return rb_obj_freeze(mod); }
Invokes Module.append_features on each parameter in turn.
/* * call-seq: * include(module, ...) => self * * Invokes <code>Module.append_features</code> on each parameter in turn. */ static VALUE rb_mod_include(argc, argv, module) int argc; VALUE *argv; VALUE module; { int i; for (i=0; i<argc; i++) Check_Type(argv[i], T_MODULE); while (argc--) { rb_funcall(argv[argc], rb_intern("append_features"), 1, module); rb_funcall(argv[argc], rb_intern("included"), 1, module); } return module; }
Returns true if module is included in mod or one of mod‘s ancestors.
module A end class B include A end class C < B end B.include?(A) #=> true C.include?(A) #=> true A.include?(A) #=> false
/* * call-seq: * mod.include?(module) => true or false * * Returns <code>true</code> if <i>module</i> is included in * <i>mod</i> or one of <i>mod</i>'s ancestors. * * module A * end * class B * include A * end * class C < B * end * B.include?(A) #=> true * C.include?(A) #=> true * A.include?(A) #=> false */ VALUE rb_mod_include_p(mod, mod2) VALUE mod; VALUE mod2; { VALUE p; Check_Type(mod2, T_MODULE); for (p = RCLASS(mod)->super; p; p = RCLASS(p)->super) { if (BUILTIN_TYPE(p) == T_ICLASS) { if (RBASIC(p)->klass == mod2) return Qtrue; } } return Qfalse; }
Callback invoked whenever the receiver is included in another module or class. This should be used in preference to Module.append_features if your code wants to perform some action when a module is included in another.
module A def A.included(mod) puts "#{self} included in #{mod}" end end module Enumerable include A end
/* * Not documented */ static VALUE rb_obj_dummy() { return Qnil; }
Returns the list of modules included in mod.
module Mixin end module Outer include Mixin end Mixin.included_modules #=> [] Outer.included_modules #=> [Mixin]
/* * call-seq: * mod.included_modules -> array * * Returns the list of modules included in <i>mod</i>. * * module Mixin * end * * module Outer * include Mixin * end * * Mixin.included_modules #=> [] * Outer.included_modules #=> [Mixin] */ VALUE rb_mod_included_modules(mod) VALUE mod; { VALUE ary = rb_ary_new(); VALUE p; for (p = RCLASS(mod)->super; p; p = RCLASS(p)->super) { if (BUILTIN_TYPE(p) == T_ICLASS) { rb_ary_push(ary, RBASIC(p)->klass); } } return ary; }
Returns an UnboundMethod representing the given instance method in mod.
class Interpreter def do_a() print "there, "; end def do_d() print "Hello "; end def do_e() print "!\n"; end def do_v() print "Dave"; end Dispatcher = { ?a => instance_method(:do_a), ?d => instance_method(:do_d), ?e => instance_method(:do_e), ?v => instance_method(:do_v) } def interpret(string) string.each_byte {|b| Dispatcher[b].bind(self).call } end end interpreter = Interpreter.new interpreter.interpret('dave')
produces:
Hello there, Dave!
/* * call-seq: * mod.instance_method(symbol) => unbound_method * * Returns an +UnboundMethod+ representing the given * instance method in _mod_. * * class Interpreter * def do_a() print "there, "; end * def do_d() print "Hello "; end * def do_e() print "!\n"; end * def do_v() print "Dave"; end * Dispatcher = { * ?a => instance_method(:do_a), * ?d => instance_method(:do_d), * ?e => instance_method(:do_e), * ?v => instance_method(:do_v) * } * def interpret(string) * string.each_byte {|b| Dispatcher[b].bind(self).call } * end * end * * * interpreter = Interpreter.new * interpreter.interpret('dave') * * <em>produces:</em> * * Hello there, Dave! */ static VALUE rb_mod_method(mod, vid) VALUE mod; VALUE vid; { return mnew(mod, Qundef, rb_to_id(vid), rb_cUnboundMethod); }
Returns an array containing the names of public instance methods in the receiver. For a module, these are the public methods; for a class, they are the instance (not singleton) methods. With no argument, or with an argument that is false, the instance methods in mod are returned, otherwise the methods in mod and mod‘s superclasses are returned.
module A def method1() end end class B def method2() end end class C < B def method3() end end A.instance_methods #=> ["method1"] B.instance_methods(false) #=> ["method2"] C.instance_methods(false) #=> ["method3"] C.instance_methods(true).length #=> 43
/* * call-seq: * mod.instance_methods(include_super=true) => array * * Returns an array containing the names of public instance methods in * the receiver. For a module, these are the public methods; for a * class, they are the instance (not singleton) methods. With no * argument, or with an argument that is <code>false</code>, the * instance methods in <i>mod</i> are returned, otherwise the methods * in <i>mod</i> and <i>mod</i>'s superclasses are returned. * * module A * def method1() end * end * class B * def method2() end * end * class C < B * def method3() end * end * * A.instance_methods #=> ["method1"] * B.instance_methods(false) #=> ["method2"] * C.instance_methods(false) #=> ["method3"] * C.instance_methods(true).length #=> 43 */ VALUE rb_class_instance_methods(argc, argv, mod) int argc; VALUE *argv; VALUE mod; { return class_instance_method_list(argc, argv, mod, ins_methods_i); }
Returns true if the named method is defined by mod (or its included modules and, if mod is a class, its ancestors). Public and protected methods are matched.
module A def method1() end end class B def method2() end end class C < B include A def method3() end end A.method_defined? :method1 #=> true C.method_defined? "method1" #=> true C.method_defined? "method2" #=> true C.method_defined? "method3" #=> true C.method_defined? "method4" #=> false
/* * call-seq: * mod.method_defined?(symbol) => true or false * * Returns +true+ if the named method is defined by * _mod_ (or its included modules and, if _mod_ is a class, * its ancestors). Public and protected methods are matched. * * module A * def method1() end * end * class B * def method2() end * end * class C < B * include A * def method3() end * end * * A.method_defined? :method1 #=> true * C.method_defined? "method1" #=> true * C.method_defined? "method2" #=> true * C.method_defined? "method3" #=> true * C.method_defined? "method4" #=> false */ static VALUE rb_mod_method_defined(mod, mid) VALUE mod, mid; { return rb_method_boundp(mod, rb_to_id(mid), 1); }
Evaluates the string or block in the context of mod. This can be used to add methods to a class. module_eval returns the result of evaluating its argument. The optional filename and lineno parameters set the text for error messages.
class Thing end a = %q{def hello() "Hello there!" end} Thing.module_eval(a) puts Thing.new.hello() Thing.module_eval("invalid code", "dummy", 123)
produces:
Hello there! dummy:123:in `module_eval': undefined local variable or method `code' for Thing:Class
/* * call-seq: * mod.class_eval(string [, filename [, lineno]]) => obj * mod.module_eval {|| block } => obj * * Evaluates the string or block in the context of _mod_. This can * be used to add methods to a class. <code>module_eval</code> returns * the result of evaluating its argument. The optional _filename_ * and _lineno_ parameters set the text for error messages. * * class Thing * end * a = %q{def hello() "Hello there!" end} * Thing.module_eval(a) * puts Thing.new.hello() * Thing.module_eval("invalid code", "dummy", 123) * * <em>produces:</em> * * Hello there! * dummy:123:in `module_eval': undefined local variable * or method `code' for Thing:Class */ VALUE rb_mod_module_eval(argc, argv, mod) int argc; VALUE *argv; VALUE mod; { return specific_eval(argc, argv, mod, mod); }
Evaluates the given block in the context of the class/module. The method defined in the block will belong to the receiver.
class Thing end Thing.class_exec{ def hello() "Hello there!" end } puts Thing.new.hello()
produces:
Hello there!
/* * call-seq: * mod.module_exec(arg...) {|var...| block } => obj * mod.class_exec(arg...) {|var...| block } => obj * * Evaluates the given block in the context of the class/module. * The method defined in the block will belong to the receiver. * * class Thing * end * Thing.class_exec{ * def hello() "Hello there!" end * } * puts Thing.new.hello() * * <em>produces:</em> * * Hello there! */ VALUE rb_mod_module_exec(argc, argv, mod) int argc; VALUE *argv; VALUE mod; { return yield_under(mod, mod, rb_ary_new4(argc, argv)); }
Creates module functions for the named methods. These functions may be called with the module as a receiver, and also become available as instance methods to classes that mix in the module. Module functions are copies of the original, and so may be changed independently. The instance-method versions are made private. If used with no arguments, subsequently defined methods become module functions.
module Mod def one "This is one" end module_function :one end class Cls include Mod def callOne one end end Mod.one #=> "This is one" c = Cls.new c.callOne #=> "This is one" module Mod def one "This is the new one" end end Mod.one #=> "This is one" c.callOne #=> "This is the new one"
/* * call-seq: * module_function(symbol, ...) => self * * Creates module functions for the named methods. These functions may * be called with the module as a receiver, and also become available * as instance methods to classes that mix in the module. Module * functions are copies of the original, and so may be changed * independently. The instance-method versions are made private. If * used with no arguments, subsequently defined methods become module * functions. * * module Mod * def one * "This is one" * end * module_function :one * end * class Cls * include Mod * def callOne * one * end * end * Mod.one #=> "This is one" * c = Cls.new * c.callOne #=> "This is one" * module Mod * def one * "This is the new one" * end * end * Mod.one #=> "This is one" * c.callOne #=> "This is the new one" */ static VALUE rb_mod_modfunc(argc, argv, module) int argc; VALUE *argv; VALUE module; { int i; ID id; NODE *body; if (TYPE(module) != T_MODULE) { rb_raise(rb_eTypeError, "module_function must be called for modules"); } secure_visibility(module); if (argc == 0) { SCOPE_SET(SCOPE_MODFUNC); return module; } set_method_visibility(module, argc, argv, NOEX_PRIVATE); for (i=0; i<argc; i++) { VALUE m = module; id = rb_to_id(argv[i]); for (;;) { body = search_method(m, id, &m); if (body == 0) { body = search_method(rb_cObject, id, &m); } if (body == 0 || body->nd_body == 0) { rb_bug("undefined method `%s'; can't happen", rb_id2name(id)); } if (nd_type(body->nd_body) != NODE_ZSUPER) { break; /* normal case: need not to follow 'super' link */ } m = RCLASS(m)->super; if (!m) break; } rb_add_method(rb_singleton_class(module), id, body->nd_body, NOEX_PUBLIC); } return module; }
With no arguments, sets the default visibility for subsequently defined methods to private. With arguments, sets the named methods to have private visibility.
module Mod def a() end def b() end private def c() end private :a end Mod.private_instance_methods #=> ["a", "c"]
/* * call-seq: * private => self * private(symbol, ...) => self * * With no arguments, sets the default visibility for subsequently * defined methods to private. With arguments, sets the named methods * to have private visibility. * * module Mod * def a() end * def b() end * private * def c() end * private :a * end * Mod.private_instance_methods #=> ["a", "c"] */ static VALUE rb_mod_private(argc, argv, module) int argc; VALUE *argv; VALUE module; { secure_visibility(module); if (argc == 0) { SCOPE_SET(SCOPE_PRIVATE); } else { set_method_visibility(module, argc, argv, NOEX_PRIVATE); } return module; }
Makes existing class methods private. Often used to hide the default constructor new.
class SimpleSingleton # Not thread safe private_class_method :new def SimpleSingleton.create(*args, &block) @me = new(*args, &block) if ! @me @me end end
/* * call-seq: * mod.private_class_method(symbol, ...) => mod * * Makes existing class methods private. Often used to hide the default * constructor <code>new</code>. * * class SimpleSingleton # Not thread safe * private_class_method :new * def SimpleSingleton.create(*args, &block) * @me = new(*args, &block) if ! @me * @me * end * end */ static VALUE rb_mod_private_method(argc, argv, obj) int argc; VALUE *argv; VALUE obj; { set_method_visibility(CLASS_OF(obj), argc, argv, NOEX_PRIVATE); return obj; }
Returns a list of the private instance methods defined in mod. If the optional parameter is not false, the methods of any ancestors are included.
module Mod def method1() end private :method1 def method2() end end Mod.instance_methods #=> ["method2"] Mod.private_instance_methods #=> ["method1"]
/* * call-seq: * mod.private_instance_methods(include_super=true) => array * * Returns a list of the private instance methods defined in * <i>mod</i>. If the optional parameter is not <code>false</code>, the * methods of any ancestors are included. * * module Mod * def method1() end * private :method1 * def method2() end * end * Mod.instance_methods #=> ["method2"] * Mod.private_instance_methods #=> ["method1"] */ VALUE rb_class_private_instance_methods(argc, argv, mod) int argc; VALUE *argv; VALUE mod; { return class_instance_method_list(argc, argv, mod, ins_methods_priv_i); }
Returns true if the named private method is defined by _ mod_ (or its included modules and, if mod is a class, its ancestors).
module A def method1() end end class B private def method2() end end class C < B include A def method3() end end A.method_defined? :method1 #=> true C.private_method_defined? "method1" #=> false C.private_method_defined? "method2" #=> true C.method_defined? "method2" #=> false
/* * call-seq: * mod.private_method_defined?(symbol) => true or false * * Returns +true+ if the named private method is defined by * _ mod_ (or its included modules and, if _mod_ is a class, * its ancestors). * * module A * def method1() end * end * class B * private * def method2() end * end * class C < B * include A * def method3() end * end * * A.method_defined? :method1 #=> true * C.private_method_defined? "method1" #=> false * C.private_method_defined? "method2" #=> true * C.method_defined? "method2" #=> false */ static VALUE rb_mod_private_method_defined(mod, mid) VALUE mod, mid; { ID id = rb_to_id(mid); int noex; if (rb_get_method_body(&mod, &id, &noex)) { if (VISI_CHECK(noex, NOEX_PRIVATE)) return Qtrue; } return Qfalse; }
With no arguments, sets the default visibility for subsequently defined methods to protected. With arguments, sets the named methods to have protected visibility.
/* * call-seq: * protected => self * protected(symbol, ...) => self * * With no arguments, sets the default visibility for subsequently * defined methods to protected. With arguments, sets the named methods * to have protected visibility. */ static VALUE rb_mod_protected(argc, argv, module) int argc; VALUE *argv; VALUE module; { secure_visibility(module); if (argc == 0) { SCOPE_SET(SCOPE_PROTECTED); } else { set_method_visibility(module, argc, argv, NOEX_PROTECTED); } return module; }
Returns a list of the protected instance methods defined in mod. If the optional parameter is not false, the methods of any ancestors are included.
/* * call-seq: * mod.protected_instance_methods(include_super=true) => array * * Returns a list of the protected instance methods defined in * <i>mod</i>. If the optional parameter is not <code>false</code>, the * methods of any ancestors are included. */ VALUE rb_class_protected_instance_methods(argc, argv, mod) int argc; VALUE *argv; VALUE mod; { return class_instance_method_list(argc, argv, mod, ins_methods_prot_i); }
Returns true if the named protected method is defined by mod (or its included modules and, if mod is a class, its ancestors).
module A def method1() end end class B protected def method2() end end class C < B include A def method3() end end A.method_defined? :method1 #=> true C.protected_method_defined? "method1" #=> false C.protected_method_defined? "method2" #=> true C.method_defined? "method2" #=> true
/* * call-seq: * mod.protected_method_defined?(symbol) => true or false * * Returns +true+ if the named protected method is defined * by _mod_ (or its included modules and, if _mod_ is a * class, its ancestors). * * module A * def method1() end * end * class B * protected * def method2() end * end * class C < B * include A * def method3() end * end * * A.method_defined? :method1 #=> true * C.protected_method_defined? "method1" #=> false * C.protected_method_defined? "method2" #=> true * C.method_defined? "method2" #=> true */ static VALUE rb_mod_protected_method_defined(mod, mid) VALUE mod, mid; { ID id = rb_to_id(mid); int noex; if (rb_get_method_body(&mod, &id, &noex)) { if (VISI_CHECK(noex, NOEX_PROTECTED)) return Qtrue; } return Qfalse; }
With no arguments, sets the default visibility for subsequently defined methods to public. With arguments, sets the named methods to have public visibility.
/* * call-seq: * public => self * public(symbol, ...) => self * * With no arguments, sets the default visibility for subsequently * defined methods to public. With arguments, sets the named methods to * have public visibility. */ static VALUE rb_mod_public(argc, argv, module) int argc; VALUE *argv; VALUE module; { secure_visibility(module); if (argc == 0) { SCOPE_SET(SCOPE_PUBLIC); } else { set_method_visibility(module, argc, argv, NOEX_PUBLIC); } return module; }
Makes a list of existing class methods public.
/* * call-seq: * mod.public_class_method(symbol, ...) => mod * * Makes a list of existing class methods public. */ static VALUE rb_mod_public_method(argc, argv, obj) int argc; VALUE *argv; VALUE obj; { set_method_visibility(CLASS_OF(obj), argc, argv, NOEX_PUBLIC); return obj; }
Returns a list of the public instance methods defined in mod. If the optional parameter is not false, the methods of any ancestors are included.
/* * call-seq: * mod.public_instance_methods(include_super=true) => array * * Returns a list of the public instance methods defined in <i>mod</i>. * If the optional parameter is not <code>false</code>, the methods of * any ancestors are included. */ VALUE rb_class_public_instance_methods(argc, argv, mod) int argc; VALUE *argv; VALUE mod; { return class_instance_method_list(argc, argv, mod, ins_methods_pub_i); }
Returns true if the named public method is defined by mod (or its included modules and, if mod is a class, its ancestors).
module A def method1() end end class B protected def method2() end end class C < B include A def method3() end end A.method_defined? :method1 #=> true C.public_method_defined? "method1" #=> true C.public_method_defined? "method2" #=> false C.method_defined? "method2" #=> true
/* * call-seq: * mod.public_method_defined?(symbol) => true or false * * Returns +true+ if the named public method is defined by * _mod_ (or its included modules and, if _mod_ is a class, * its ancestors). * * module A * def method1() end * end * class B * protected * def method2() end * end * class C < B * include A * def method3() end * end * * A.method_defined? :method1 #=> true * C.public_method_defined? "method1" #=> true * C.public_method_defined? "method2" #=> false * C.method_defined? "method2" #=> true */ static VALUE rb_mod_public_method_defined(mod, mid) VALUE mod, mid; { ID id = rb_to_id(mid); int noex; if (rb_get_method_body(&mod, &id, &noex)) { if (VISI_CHECK(noex, NOEX_PUBLIC)) return Qtrue; } return Qfalse; }
Removes the definition of the sym, returning that constant‘s value.
class Dummy @@var = 99 puts @@var remove_class_variable(:@@var) puts(defined? @@var) end
produces:
99 nil
/* * call-seq: * remove_class_variable(sym) => obj * * Removes the definition of the <i>sym</i>, returning that * constant's value. * * class Dummy * @@var = 99 * puts @@var * remove_class_variable(:@@var) * puts(defined? @@var) * end * * <em>produces:</em> * * 99 * nil */ VALUE rb_mod_remove_cvar(mod, name) VALUE mod, name; { ID id = rb_to_id(name); VALUE val; if (!rb_is_class_id(id)) { rb_name_error(id, "wrong class variable name %s", rb_id2name(id)); } if (!OBJ_TAINTED(mod) && rb_safe_level() >= 4) rb_raise(rb_eSecurityError, "Insecure: can't remove class variable"); if (OBJ_FROZEN(mod)) rb_error_frozen("class/module"); if (RCLASS(mod)->iv_tbl && st_delete(ROBJECT(mod)->iv_tbl, (st_data_t*)&id, &val)) { return val; } if (rb_cvar_defined(mod, id)) { rb_name_error(id, "cannot remove %s for %s", rb_id2name(id), rb_class2name(mod)); } rb_name_error(id, "class variable %s not defined for %s", rb_id2name(id), rb_class2name(mod)); return Qnil; /* not reached */ }
Removes the definition of the given constant, returning that constant‘s value. Predefined classes and singleton objects (such as true) cannot be removed.
/* * call-seq: * remove_const(sym) => obj * * Removes the definition of the given constant, returning that * constant's value. Predefined classes and singleton objects (such as * <i>true</i>) cannot be removed. */ VALUE rb_mod_remove_const(mod, name) VALUE mod, name; { ID id = rb_to_id(name); VALUE val; if (!rb_is_const_id(id)) { rb_name_error(id, "`%s' is not allowed as a constant name", rb_id2name(id)); } if (!OBJ_TAINTED(mod) && rb_safe_level() >= 4) rb_raise(rb_eSecurityError, "Insecure: can't remove constant"); if (OBJ_FROZEN(mod)) rb_error_frozen("class/module"); if (RCLASS(mod)->iv_tbl && st_delete(ROBJECT(mod)->iv_tbl, (st_data_t*)&id, &val)) { if (val == Qundef) { autoload_delete(mod, id); val = Qnil; } return val; } if (rb_const_defined_at(mod, id)) { rb_name_error(id, "cannot remove %s::%s", rb_class2name(mod), rb_id2name(id)); } rb_name_error(id, "constant %s::%s not defined", rb_class2name(mod), rb_id2name(id)); return Qnil; /* not reached */ }
Removes the method identified by symbol from the current class. For an example, see Module.undef_method.
/* * call-seq: * remove_method(symbol) => self * * Removes the method identified by _symbol_ from the current * class. For an example, see <code>Module.undef_method</code>. */ static VALUE rb_mod_remove_method(argc, argv, mod) int argc; VALUE *argv; VALUE mod; { int i; for (i=0; i<argc; i++) { remove_method(mod, rb_to_id(argv[i])); } return mod; }
Return a string representing this module or class. For basic classes and modules, this is the name. For singletons, we show information on the thing we‘re attached to as well.
/* * call-seq: * mod.to_s => string * * Return a string representing this module or class. For basic * classes and modules, this is the name. For singletons, we * show information on the thing we're attached to as well. */ static VALUE rb_mod_to_s(klass) VALUE klass; { if (FL_TEST(klass, FL_SINGLETON)) { VALUE s = rb_str_new2("#<"); VALUE v = rb_iv_get(klass, "__attached__"); rb_str_cat2(s, "Class:"); switch (TYPE(v)) { case T_CLASS: case T_MODULE: rb_str_append(s, rb_inspect(v)); break; default: rb_str_append(s, rb_any_to_s(v)); break; } rb_str_cat2(s, ">"); return s; } return rb_str_dup(rb_class_name(klass)); }
Prevents the current class from responding to calls to the named method. Contrast this with remove_method, which deletes the method from the particular class; Ruby will still search superclasses and mixed-in modules for a possible receiver.
class Parent def hello puts "In parent" end end class Child < Parent def hello puts "In child" end end c = Child.new c.hello class Child remove_method :hello # remove from child, still in parent end c.hello class Child undef_method :hello # prevent any calls to 'hello' end c.hello
produces:
In child In parent prog.rb:23: undefined method `hello' for #<Child:0x401b3bb4> (NoMethodError)
/* * call-seq: * undef_method(symbol) => self * * Prevents the current class from responding to calls to the named * method. Contrast this with <code>remove_method</code>, which deletes * the method from the particular class; Ruby will still search * superclasses and mixed-in modules for a possible receiver. * * class Parent * def hello * puts "In parent" * end * end * class Child < Parent * def hello * puts "In child" * end * end * * * c = Child.new * c.hello * * * class Child * remove_method :hello # remove from child, still in parent * end * c.hello * * * class Child * undef_method :hello # prevent any calls to 'hello' * end * c.hello * * <em>produces:</em> * * In child * In parent * prog.rb:23: undefined method `hello' for #<Child:0x401b3bb4> (NoMethodError) */ static VALUE rb_mod_undef_method(argc, argv, mod) int argc; VALUE *argv; VALUE mod; { int i; for (i=0; i<argc; i++) { rb_undef(mod, rb_to_id(argv[i])); } return mod; }