Class: Module

Inherits:
Object show all
Defined in:
object.c,
class.c,
object.c

Overview

*********************************************************************

A <code>Module</code> 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 <code>Module#module_function</code>)

In the descriptions that follow, the parameter <i>sym</i> refers
to a symbol, which is either a quoted string or a
<code>Symbol</code> (such as <code>:name</code>).

   module Mod
     include Math
     CONST = 1
     def meth
       #  ...
     end
   end
   Mod.class              #=> Module
   Mod.constants          #=> [:CONST, :PI, :E]
   Mod.instance_methods   #=> [:meth]

Direct Known Subclasses

Class

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#newObject #new {|mod| ... } ⇒ Object

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"

Assign the module to a constant (name starting uppercase) if you want to treat it like a regular module.

Overloads:

  • #new {|mod| ... } ⇒ Object

    Yields:

    • (mod)


1600
1601
1602
1603
1604
1605
1606
1607
# File 'object.c', line 1600

static VALUE
rb_mod_initialize(VALUE module)
{
    if (rb_block_given_p()) {
	rb_mod_module_exec(1, &module, module);
    }
    return Qnil;
}

Class Method Details

.constantsArray .constants(inherited) ⇒ Array

In the first form, returns an array of the names of all constants accessible from the point of call. This list includes the names of all modules and classes defined in the global scope.

Module.constants.first(4)
   # => [:ARGF, :ARGV, :ArgumentError, :Array]

Module.constants.include?(:SEEK_SET)   # => false

class IO
  Module.constants.include?(:SEEK_SET) # => true
end

The second form calls the instance method constants.

Overloads:



372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
# File 'eval.c', line 372

static VALUE
rb_mod_s_constants(int argc, VALUE *argv, VALUE mod)
{
    const NODE *cref = rb_vm_cref();
    VALUE klass;
    VALUE cbase = 0;
    void *data = 0;

    if (argc > 0) {
	return rb_mod_constants(argc, argv, rb_cModule);
    }

    while (cref) {
	klass = cref->nd_clss;
	if (!(cref->flags & NODE_FL_CREF_PUSHED_BY_EVAL) &&
	    !NIL_P(klass)) {
	    data = rb_mod_const_at(cref->nd_clss, data);
	    if (!cbase) {
		cbase = klass;
	    }
	}
	cref = cref->nd_next;
    }

    if (cbase) {
	data = rb_mod_const_of(cbase, data);
    }
    return rb_const_list(data);
}

.nestingArray

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"

Returns:



333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
# File 'eval.c', line 333

static VALUE
rb_mod_nesting(void)
{
    VALUE ary = rb_ary_new();
    const NODE *cref = rb_vm_cref();

    while (cref && cref->nd_next) {
	VALUE klass = cref->nd_clss;
	if (!(cref->flags & NODE_FL_CREF_PUSHED_BY_EVAL) &&
	    !NIL_P(klass)) {
	    rb_ary_push(ary, klass);
	}
	cref = cref->nd_next;
    }
    return ary;
}

Instance Method Details

#<(other) ⇒ true, ...

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").

Returns:

  • (true, false, nil)


1482
1483
1484
1485
1486
1487
# File 'object.c', line 1482

static VALUE
rb_mod_lt(VALUE mod, VALUE arg)
{
    if (mod == arg) return Qfalse;
    return rb_class_inherited_p(mod, arg);
}

#<=(other) ⇒ true, ...

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").

Returns:

  • (true, false, nil)


1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
# File 'object.c', line 1448

VALUE
rb_class_inherited_p(VALUE mod, VALUE arg)
{
    VALUE start = mod;

    if (mod == arg) return Qtrue;
    if (!CLASS_OR_MODULE_P(arg)) {
	rb_raise(rb_eTypeError, "compared with non class/module");
    }
    while (mod) {
	if (RCLASS_M_TBL(mod) == RCLASS_M_TBL(arg))
	    return Qtrue;
	mod = RCLASS_SUPER(mod);
    }
    /* not mod < arg; check if mod > arg */
    while (arg) {
	if (RCLASS_M_TBL(arg) == RCLASS_M_TBL(start))
	    return Qfalse;
	arg = RCLASS_SUPER(arg);
    }
    return Qnil;
}

#<=>(other_mod) ⇒ -1, ...

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. Returns nil if mod has no relationship with other_mod or if other_mod is not a module.

Returns:

  • (-1, 0, +1, nil)


1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
# File 'object.c', line 1541

static VALUE
rb_mod_cmp(VALUE mod, VALUE arg)
{
    VALUE cmp;

    if (mod == arg) return INT2FIX(0);
    if (!CLASS_OR_MODULE_P(arg)) {
	return Qnil;
    }

    cmp = rb_class_inherited_p(mod, arg);
    if (NIL_P(cmp)) return Qnil;
    if (cmp) {
	return INT2FIX(-1);
    }
    return INT2FIX(1);
}

#==(other) ⇒ Boolean #equal?(other) ⇒ Boolean #eql?(other) ⇒ Boolean

Equality --- At the Object level, == returns true only if obj and other are the same object. Typically, this method is overridden in descendant classes to provide class-specific meaning.

Unlike ==, the equal? method should never be overridden by subclasses as it is used to determine object identity (that is, a.equal?(b) if and only if a is the same object as b):

obj = "a"
other = obj.dup

a == other      #=> true
a.equal? other  #=> false
a.equal? a      #=> true

The eql? method returns true if obj and other refer to the same hash key. This is used by Hash to test members for equality. For objects of class Object, 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     #=> true
1.eql? 1.0   #=> false

Overloads:

  • #==(other) ⇒ Boolean

    Returns:

    • (Boolean)
  • #equal?(other) ⇒ Boolean

    Returns:

    • (Boolean)
  • #eql?(other) ⇒ Boolean

    Returns:

    • (Boolean)


108
109
110
111
112
113
# File 'object.c', line 108

VALUE
rb_obj_equal(VALUE obj1, VALUE obj2)
{
    if (obj1 == obj2) return Qtrue;
    return Qfalse;
}

#===(obj) ⇒ Boolean

Case Equality---Returns true if anObject is an instance of mod or one of mod's descendants. Of limited use for modules, but can be used in case statements to classify objects by class.

Returns:

  • (Boolean)


1430
1431
1432
1433
1434
# File 'object.c', line 1430

static VALUE
rb_mod_eqq(VALUE mod, VALUE arg)
{
    return rb_obj_is_kind_of(arg, mod);
}

#>(other) ⇒ true, ...

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").

Returns:

  • (true, false, nil)


1523
1524
1525
1526
1527
1528
# File 'object.c', line 1523

static VALUE
rb_mod_gt(VALUE mod, VALUE arg)
{
    if (mod == arg) return Qfalse;
    return rb_mod_ge(mod, arg);
}

#>=(other) ⇒ true, ...

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").

Returns:

  • (true, false, nil)


1502
1503
1504
1505
1506
1507
1508
1509
1510
# File 'object.c', line 1502

static VALUE
rb_mod_ge(VALUE mod, VALUE arg)
{
    if (!CLASS_OR_MODULE_P(arg)) {
	rb_raise(rb_eTypeError, "compared with non class/module");
    }

    return rb_class_inherited_p(arg, mod);
}

#alias_method(new_name, old_name) ⇒ self (private)

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

Returns:

  • (self)


1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
# File 'vm_method.c', line 1231

static VALUE
rb_mod_alias_method(VALUE mod, VALUE newname, VALUE oldname)
{
    ID oldid = rb_check_id(&oldname);
    if (!oldid) {
	rb_print_undef_str(mod, oldname);
    }
    rb_alias(mod, rb_to_id(newname), oldid);
    return mod;
}

#ancestorsArray

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]

Returns:



901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
# File 'class.c', line 901

VALUE
rb_mod_ancestors(VALUE mod)
{
    VALUE p, ary = rb_ary_new();

    for (p = mod; p; p = RCLASS_SUPER(p)) {
	if (FL_TEST(p, FL_SINGLETON))
	    continue;
	if (BUILTIN_TYPE(p) == T_ICLASS) {
	    rb_ary_push(ary, RBASIC(p)->klass);
	}
	else if (p == RCLASS_ORIGIN(p)) {
	    rb_ary_push(ary, p);
	}
    }
    return ary;
}

#append_features(mod) ⇒ Object (private)

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.



953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
# File 'eval.c', line 953

static VALUE
rb_mod_append_features(VALUE module, VALUE 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;
}

#attrObject (private)



1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
# File 'object.c', line 1816

VALUE
rb_mod_attr(int argc, VALUE *argv, VALUE klass)
{
    if (argc == 2 && (argv[1] == Qtrue || argv[1] == Qfalse)) {
	rb_warning("optional boolean argument is obsoleted");
	rb_attr(klass, rb_to_id(argv[0]), 1, RTEST(argv[1]), TRUE);
	return Qnil;
    }
    return rb_mod_attr_reader(argc, argv, klass);
}

#attr_accessor(symbol, ...) ⇒ nil (private)

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. Also creates a method called name= to set the attribute.

module Mod
  attr_accessor(:one, :two)
end
Mod.instance_methods.sort   #=> [:one, :one=, :two, :two=]

Returns:

  • (nil)


1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
# File 'object.c', line 1861

static VALUE
rb_mod_attr_accessor(int argc, VALUE *argv, VALUE klass)
{
    int i;

    for (i=0; i<argc; i++) {
	rb_attr(klass, rb_to_id(argv[i]), TRUE, TRUE, TRUE);
    }
    return Qnil;
}

#attr_reader(symbol, ...) ⇒ nil (private) #attr(symbol, ...) ⇒ nil (private)

Creates instance variables and corresponding methods that return the value of each instance variable. Equivalent to calling "attr:name" on each name in turn.

Overloads:

  • #attr_reader(symbol, ...) ⇒ nil

    Returns:

    • (nil)
  • #attr(symbol, ...) ⇒ nil

    Returns:

    • (nil)


1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
# File 'object.c', line 1805

static VALUE
rb_mod_attr_reader(int argc, VALUE *argv, VALUE klass)
{
    int i;

    for (i=0; i<argc; i++) {
	rb_attr(klass, rb_to_id(argv[i]), TRUE, FALSE, TRUE);
    }
    return Qnil;
}

#attr_writer(symbol, ...) ⇒ nil (private)

Creates an accessor method to allow assignment to the attribute symbol.id2name.

Returns:

  • (nil)


1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
# File 'object.c', line 1835

static VALUE
rb_mod_attr_writer(int argc, VALUE *argv, VALUE klass)
{
    int i;

    for (i=0; i<argc; i++) {
	rb_attr(klass, rb_to_id(argv[i]), FALSE, TRUE, TRUE);
    }
    return Qnil;
}

#autoloadnil

Registers filename to be loaded (using Kernel::require) the first time that module (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"

Returns:

  • (nil)


996
997
998
999
1000
1001
1002
1003
1004
# File 'load.c', line 996

static VALUE
rb_mod_autoload(VALUE mod, VALUE sym, VALUE file)
{
    ID id = rb_to_id(sym);

    FilePathValue(file);
    rb_autoload(mod, id, RSTRING_PTR(file));
    return Qnil;
}

#autoload?(name) ⇒ String?

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"

Returns:

Returns:

  • (Boolean)


1019
1020
1021
1022
1023
1024
1025
1026
1027
# File 'load.c', line 1019

static VALUE
rb_mod_autoload_p(VALUE mod, VALUE sym)
{
    ID id = rb_check_id(&sym);
    if (!id) {
	return Qnil;
    }
    return rb_autoload_p(mod, id);
}

#class_eval(string[, filename [, lineno]]) ⇒ Object #module_eval { ... } ⇒ Object

Evaluates the string or block in the context of mod, except that when a block is given, constant/class variable lookup is not affected. 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

Overloads:

  • #class_eval(string[, filename [, lineno]]) ⇒ Object

    Returns:

  • #module_eval { ... } ⇒ Object

    Yields:

    Returns:



1643
1644
1645
1646
1647
# File 'vm_eval.c', line 1643

VALUE
rb_mod_module_eval(int argc, VALUE *argv, VALUE mod)
{
    return specific_eval(argc, argv, mod, mod);
}

#module_exec(arg...) {|var...| ... } ⇒ Object #class_exec(arg...) {|var...| ... } ⇒ Object

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!

Overloads:

  • #module_exec(arg...) {|var...| ... } ⇒ Object

    Yields:

    • (var...)

    Returns:

  • #class_exec(arg...) {|var...| ... } ⇒ Object

    Yields:

    • (var...)

    Returns:



1669
1670
1671
1672
1673
# File 'vm_eval.c', line 1669

VALUE
rb_mod_module_exec(int argc, VALUE *argv, VALUE mod)
{
    return yield_under(mod, mod, rb_ary_new4(argc, argv));
}

#class_variable_defined?(symbol) ⇒ Boolean

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

Returns:

  • (Boolean)

Returns:

  • (Boolean)


2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
# File 'object.c', line 2264

static VALUE
rb_mod_cvar_defined(VALUE obj, VALUE iv)
{
    ID id = rb_check_id(&iv);

    if (!id) {
	if (rb_is_class_name(iv)) {
	    return Qfalse;
	}
	else {
	    rb_name_error_str(iv, "`%"PRIsVALUE"' is not allowed as a class variable name",
			      QUOTE(iv));
	}
    }
    if (!rb_is_class_id(id)) {
	rb_name_error(id, "`%"PRIsVALUE"' is not allowed as a class variable name",
		      QUOTE_ID(id));
    }
    return rb_cvar_defined(obj, id);
}

#class_variable_get(symbol) ⇒ Object

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
Fred.class_variable_get(:@@foo)     #=> 99

Returns:



2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
# File 'object.c', line 2198

static VALUE
rb_mod_cvar_get(VALUE obj, VALUE iv)
{
    ID id = rb_check_id(&iv);

    if (!id) {
	if (rb_is_class_name(iv)) {
	    rb_name_error_str(iv, "uninitialized class variable %"PRIsVALUE" in %"PRIsVALUE"",
			      iv, rb_class_name(obj));
	}
	else {
	    rb_name_error_str(iv, "`%"PRIsVALUE"' is not allowed as a class variable name",
			      QUOTE(iv));
	}
    }
    if (!rb_is_class_id(id)) {
	rb_name_error(id, "`%"PRIsVALUE"' is not allowed as a class variable name",
		      QUOTE_ID(id));
    }
    return rb_cvar_get(obj, id);
}

#class_variable_set(symbol, obj) ⇒ Object

Sets the class variable names by symbol to object.

class Fred
  @@foo = 99
  def foo
    @@foo
  end
end
Fred.class_variable_set(:@@foo, 101)     #=> 101
Fred.new.foo                             #=> 101

Returns:



2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
# File 'object.c', line 2237

static VALUE
rb_mod_cvar_set(VALUE obj, VALUE iv, VALUE val)
{
    ID id = rb_to_id(iv);

    if (!rb_is_class_id(id)) {
	rb_name_error(id, "`%"PRIsVALUE"' is not allowed as a class variable name",
		      QUOTE_ID(id));
    }
    rb_cvar_set(obj, id, val);
    return val;
}

#class_variables(inherit = true) ⇒ Array

Returns an array of the names of class variables in mod. This includes the names of class variables in any included modules, unless the inherit parameter is set to false.

class One
  @@var1 = 1
end
class Two < One
  @@var2 = 2
end
One.class_variables   #=> [:@@var1]
Two.class_variables   #=> [:@@var2, :@@var1]

Returns:



2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
# File 'variable.c', line 2502

VALUE
rb_mod_class_variables(int argc, VALUE *argv, VALUE mod)
{
    VALUE inherit;
    st_table *tbl;

    if (argc == 0) {
	inherit = Qtrue;
    }
    else {
	rb_scan_args(argc, argv, "01", &inherit);
    }
    if (RTEST(inherit)) {
	tbl = mod_cvar_of(mod, 0);
    }
    else {
	tbl = mod_cvar_at(mod, 0);
    }
    return cvar_list(tbl);
}

#const_defined?(sym, inherit = true) ⇒ Boolean

Checks for a constant with the given name in mod If inherit is set, the lookup will also search the ancestors (and Object if mod is a Module.)

Returns whether or not a definition is found:

Math.const_defined? "PI"   #=> true
IO.const_defined? :SYNC   #=> true
IO.const_defined? :SYNC, false   #=> false

Returns:

  • (Boolean)

Returns:

  • (Boolean)


2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
# File 'object.c', line 2043

static VALUE
rb_mod_const_defined(int argc, VALUE *argv, VALUE mod)
{
    VALUE name, recur;
    ID id;

    if (argc == 1) {
	name = argv[0];
	recur = Qtrue;
    }
    else {
	rb_scan_args(argc, argv, "11", &name, &recur);
    }
    if (!(id = rb_check_id(&name))) {
	if (rb_is_const_name(name)) {
	    return Qfalse;
	}
	else {
	    rb_name_error_str(name, "wrong constant name %"PRIsVALUE,
			      QUOTE(name));
	}
    }
    if (!rb_is_const_id(id)) {
	rb_name_error(id, "wrong constant name %"PRIsVALUE,
		      QUOTE_ID(id));
    }
    return RTEST(recur) ? rb_const_defined(mod, id) : rb_const_defined_at(mod, id);
}

#const_get(sym, inherit = true) ⇒ Object #const_get(str, inherit = true) ⇒ Object

Checks for a constant with the given name in mod If inherit is set, the lookup will also search the ancestors (and Object if mod is a Module.)

The value of the constant is returned if a definition is found, otherwise a NameError is raised.

Math.const_get(:PI)   #=> 3.14159265358979

This method will recursively look up constant names if a namespaced class name is provided. For example:

module Foo; class Bar; end end
Object.const_get 'Foo::Bar'

The inherit flag is respected on each lookup. For example:

module Foo
  class Bar
    VAL = 10
  end

  class Baz < Bar; end
end

Object.const_get 'Foo::Baz::VAL'         # => 10
Object.const_get 'Foo::Baz::VAL', false  # => NameError

Overloads:

  • #const_get(sym, inherit = true) ⇒ Object

    Returns:

  • #const_get(str, inherit = true) ⇒ Object

    Returns:



1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
# File 'object.c', line 1906

static VALUE
rb_mod_const_get(int argc, VALUE *argv, VALUE mod)
{
    VALUE name, recur;
    rb_encoding *enc;
    const char *pbeg, *p, *path, *pend;
    ID id;
    int nestable = 1;

    if (argc == 1) {
	name = argv[0];
	recur = Qtrue;
    }
    else {
	rb_scan_args(argc, argv, "11", &name, &recur);
    }

    if (SYMBOL_P(name)) {
	name = rb_sym_to_s(name);
	nestable = 0;
    }

    name = rb_check_string_type(name);
    Check_Type(name, T_STRING);

    enc = rb_enc_get(name);
    path = RSTRING_PTR(name);

    if (!rb_enc_asciicompat(enc)) {
	rb_raise(rb_eArgError, "invalid class path encoding (non ASCII)");
    }

    pbeg = p = path;
    pend = path + RSTRING_LEN(name);

    if (p >= pend || !*p) {
      wrong_name:
	rb_raise(rb_eNameError, "wrong constant name %"PRIsVALUE,
		 QUOTE(name));
    }

    if (p + 2 < pend && p[0] == ':' && p[1] == ':') {
	if (!nestable) goto wrong_name;
	mod = rb_cObject;
	p += 2;
	pbeg = p;
    }

    while (p < pend) {
	VALUE part;
	long len, beglen;

	while (p < pend && *p != ':') p++;

	if (pbeg == p) goto wrong_name;

	id = rb_check_id_cstr(pbeg, len = p-pbeg, enc);
	beglen = pbeg-path;

	if (p < pend && p[0] == ':') {
	    if (!nestable) goto wrong_name;
	    if (p + 2 >= pend || p[1] != ':') goto wrong_name;
	    p += 2;
	    pbeg = p;
	}

	if (!RB_TYPE_P(mod, T_MODULE) && !RB_TYPE_P(mod, T_CLASS)) {
	    rb_raise(rb_eTypeError, "%"PRIsVALUE" does not refer to class/module",
		     QUOTE(name));
	}

	if (!id) {
	    if (!ISUPPER(*pbeg) || !rb_enc_symname2_p(pbeg, len, enc)) {
		part = rb_str_subseq(name, beglen, len);
		rb_name_error_str(part, "wrong constant name %"PRIsVALUE,
				  QUOTE(part));
	    }
	    else if (!rb_method_basic_definition_p(CLASS_OF(mod), id_const_missing)) {
		id = rb_intern3(pbeg, len, enc);
	    }
	    else {
		part = rb_str_subseq(name, beglen, len);
		rb_name_error_str(part, "uninitialized constant %"PRIsVALUE"%"PRIsVALUE,
				  rb_str_subseq(name, 0, beglen),
				  QUOTE(part));
	    }
	}
	if (!rb_is_const_id(id)) {
	    rb_name_error(id, "wrong constant name %"PRIsVALUE,
			  QUOTE_ID(id));
	}
	mod = RTEST(recur) ? rb_const_get(mod, id) : rb_const_get_at(mod, id);
    }

    return mod;
}

#const_missing(sym) ⇒ Object

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 an example of the same:

def Foo.const_missing(name)
  name # return the constant name as Symbol
end

Foo::UNDEFINED_CONST    #=> :UNDEFINED_CONST: symbol returned

In the next example when a 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 loaded class. It therefore implements an autoload feature similar to Kernel#autoload and Module#autoload.

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

Returns:



1512
1513
1514
1515
1516
1517
1518
1519
# File 'variable.c', line 1512

VALUE
rb_mod_const_missing(VALUE klass, VALUE name)
{
    rb_frame_pop(); /* pop frame for "const_missing" */
    uninitialized_constant(klass, rb_to_id(name));

    UNREACHABLE;
}

#const_set(sym, obj) ⇒ Object

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

Returns:



2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
# File 'object.c', line 2015

static VALUE
rb_mod_const_set(VALUE mod, VALUE name, VALUE value)
{
    ID id = rb_to_id(name);

    if (!rb_is_const_id(id)) {
	rb_name_error(id, "wrong constant name %"PRIsVALUE,
		      QUOTE_ID(id));
    }
    rb_const_set(mod, id, value);
    return value;
}

#constants(inherit = true) ⇒ Array

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), unless the inherit parameter is set to false.

IO.constants.include?(:SYNC)        #=> true
IO.constants(false).include?(:SYNC) #=> false

Also see Module::const_defined?.

Returns:



2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
# File 'variable.c', line 2040

VALUE
rb_mod_constants(int argc, VALUE *argv, VALUE mod)
{
    VALUE inherit;
    st_table *tbl;

    if (argc == 0) {
	inherit = Qtrue;
    }
    else {
	rb_scan_args(argc, argv, "01", &inherit);
    }
    if (RTEST(inherit)) {
	tbl = rb_mod_const_of(mod, 0);
    }
    else {
	tbl = rb_mod_const_at(mod, 0);
    }
    return rb_const_list(tbl);
}

#define_method(symbol, method) ⇒ Object (private) #define_method(symbol) { ... } ⇒ Proc (private)

Defines an instance method in the receiver. The method parameter can be a Proc, a Method or an UnboundMethod 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>

Overloads:

  • #define_method(symbol) { ... } ⇒ Proc

    Yields:

    Returns:



1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
# File 'proc.c', line 1358

static VALUE
rb_mod_define_method(int argc, VALUE *argv, VALUE mod)
{
    ID id;
    VALUE body;
    int noex = NOEX_PUBLIC;

    if (argc == 1) {
	id = rb_to_id(argv[0]);
	body = rb_block_lambda();
    }
    else {
	rb_check_arity(argc, 1, 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));
	}
    }

    if (rb_obj_is_method(body)) {
	struct METHOD *method = (struct METHOD *)DATA_PTR(body);
	VALUE rclass = method->rclass;
	if (rclass != mod && !RB_TYPE_P(rclass, T_MODULE) &&
	    !RTEST(rb_class_inherited_p(mod, rclass))) {
	    if (FL_TEST(rclass, FL_SINGLETON)) {
		rb_raise(rb_eTypeError,
			 "can't bind singleton method to a different class");
	    }
	    else {
		rb_raise(rb_eTypeError,
			 "bind argument must be a subclass of %s",
			 rb_class2name(rclass));
	    }
	}
	rb_method_entry_set(mod, id, method->me, noex);
    }
    else if (rb_obj_is_proc(body)) {
	rb_proc_t *proc;
	body = proc_dup(body);
	GetProcPtr(body, proc);
	if (BUILTIN_TYPE(proc->block.iseq) != T_NODE) {
	    proc->block.iseq->defined_method_id = id;
	    proc->block.iseq->klass = mod;
	    proc->is_lambda = TRUE;
	    proc->is_from_method = TRUE;
	    proc->block.klass = mod;
	}
	rb_add_method(mod, id, VM_METHOD_TYPE_BMETHOD, (void *)body, noex);
    }
    else {
	/* type error */
	rb_raise(rb_eTypeError, "wrong argument type (expected Proc/Method)");
    }

    return body;
}

#extend_object(obj) ⇒ Object (private)

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

Returns:



1266
1267
1268
1269
1270
1271
# File 'eval.c', line 1266

static VALUE
rb_mod_extend_object(VALUE mod, VALUE obj)
{
    rb_extend_object(obj, mod);
    return obj;
}

#extendedObject (private)

Not documented



828
829
830
831
832
# File 'object.c', line 828

static VALUE
rb_obj_dummy(void)
{
    return Qnil;
}

#freezeObject

Prevents further modifications to mod.

This method returns self.



1413
1414
1415
1416
1417
1418
# File 'object.c', line 1413

static VALUE
rb_mod_freeze(VALUE mod)
{
    rb_class_name(mod);
    return rb_obj_freeze(mod);
}

#includeself (private)

Invokes Module.append_features on each parameter in reverse order.

Returns:

  • (self)


976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
# File 'eval.c', line 976

static VALUE
rb_mod_include(int argc, VALUE *argv, VALUE module)
{
    int i;
    ID id_append_features, id_included;

    CONST_ID(id_append_features, "append_features");
    CONST_ID(id_included, "included");

    for (i = 0; i < argc; i++)
	Check_Type(argv[i], T_MODULE);
    while (argc--) {
	rb_funcall(argv[argc], id_append_features, 1, module);
	rb_funcall(argv[argc], id_included, 1, module);
    }
    return module;
}

#include?Boolean

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

Returns:

  • (Boolean)

Returns:

  • (Boolean)


871
872
873
874
875
876
877
878
879
880
881
882
883
# File 'class.c', line 871

VALUE
rb_mod_include_p(VALUE mod, VALUE mod2)
{
    VALUE p;

    Check_Type(mod2, T_MODULE);
    for (p = RCLASS_SUPER(mod); p; p = RCLASS_SUPER(p)) {
	if (BUILTIN_TYPE(p) == T_ICLASS) {
	    if (RBASIC(p)->klass == mod2) return Qtrue;
	}
    }
    return Qfalse;
}

#includedObject (private)

Not documented



828
829
830
831
832
# File 'object.c', line 828

static VALUE
rb_obj_dummy(void)
{
    return Qnil;
}

#included_modulesArray

Returns the list of modules included in mod.

module Mixin
end

module Outer
  include Mixin
end

Mixin.included_modules   #=> []
Outer.included_modules   #=> [Mixin]

Returns:



838
839
840
841
842
843
844
845
846
847
848
849
850
# File 'class.c', line 838

VALUE
rb_mod_included_modules(VALUE mod)
{
    VALUE ary = rb_ary_new();
    VALUE p;

    for (p = RCLASS_SUPER(mod); p; p = RCLASS_SUPER(p)) {
	if (BUILTIN_TYPE(p) == T_ICLASS) {
	    rb_ary_push(ary, RBASIC(p)->klass);
	}
    }
    return ary;
}

#initialize_copyObject

:nodoc:



195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
# File 'class.c', line 195

VALUE
rb_mod_init_copy(VALUE clone, VALUE orig)
{
    if (RB_TYPE_P(clone, T_CLASS)) {
	class_init_copy_check(clone, orig);
    }
    rb_obj_init_copy(clone, orig);
    if (!FL_TEST(CLASS_OF(clone), FL_SINGLETON)) {
	RBASIC(clone)->klass = rb_singleton_class_clone(orig);
	rb_singleton_class_attached(RBASIC(clone)->klass, (VALUE)clone);
    }
    RCLASS_SUPER(clone) = RCLASS_SUPER(orig);
    RCLASS_EXT(clone)->allocator = RCLASS_EXT(orig)->allocator;
    if (RCLASS_IV_TBL(orig)) {
	st_data_t id;

	if (RCLASS_IV_TBL(clone)) {
	    st_free_table(RCLASS_IV_TBL(clone));
	}
	RCLASS_IV_TBL(clone) = st_copy(RCLASS_IV_TBL(orig));
	CONST_ID(id, "__tmp_classpath__");
	st_delete(RCLASS_IV_TBL(clone), &id, 0);
	CONST_ID(id, "__classpath__");
	st_delete(RCLASS_IV_TBL(clone), &id, 0);
	CONST_ID(id, "__classid__");
	st_delete(RCLASS_IV_TBL(clone), &id, 0);
    }
    if (RCLASS_CONST_TBL(orig)) {
	if (RCLASS_CONST_TBL(clone)) {
	    rb_free_const_table(RCLASS_CONST_TBL(clone));
	}
	RCLASS_CONST_TBL(clone) = st_init_numtable();
	st_foreach(RCLASS_CONST_TBL(orig), clone_const_i, (st_data_t)RCLASS_CONST_TBL(clone));
    }
    if (RCLASS_M_TBL(orig)) {
	if (RCLASS_M_TBL(clone)) {
	    rb_free_m_table(RCLASS_M_TBL(clone));
	}
	RCLASS_M_TBL(clone) = st_init_numtable();
	st_foreach(RCLASS_M_TBL(orig), clone_method_i, (st_data_t)clone);
    }

    return clone;
}

#instance_method(symbol) ⇒ Object

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_char {|b| Dispatcher[b].bind(self).call }
  end
end

interpreter = Interpreter.new
interpreter.interpret('dave')

produces:

Hello there, Dave!


1294
1295
1296
1297
1298
1299
1300
1301
1302
# File 'proc.c', line 1294

static VALUE
rb_mod_instance_method(VALUE mod, VALUE vid)
{
    ID id = rb_check_id(&vid);
    if (!id) {
	rb_method_name_error(mod, vid);
    }
    return mnew(mod, Qundef, id, rb_cUnboundMethod, FALSE);
}

#instance_methods(include_super = true) ⇒ Array

Returns an array containing the names of the public and protected instance methods in the receiver. For a module, these are the public and protected 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

Returns:



1048
1049
1050
1051
1052
# File 'class.c', line 1048

VALUE
rb_class_instance_methods(int argc, VALUE *argv, VALUE mod)
{
    return class_instance_method_list(argc, argv, mod, 0, ins_methods_i);
}

#method_addedObject (private)

Not documented



828
829
830
831
832
# File 'object.c', line 828

static VALUE
rb_obj_dummy(void)
{
    return Qnil;
}

#method_defined?(symbol) ⇒ Boolean

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

Returns:

  • (Boolean)

Returns:

  • (Boolean)


961
962
963
964
965
966
967
968
969
970
# File 'vm_method.c', line 961

static VALUE
rb_mod_method_defined(VALUE mod, VALUE mid)
{
    ID id = rb_check_id(&mid);
    if (!id || !rb_method_boundp(mod, id, 1)) {
	return Qfalse;
    }
    return Qtrue;

}

#method_removedObject (private)

Not documented



828
829
830
831
832
# File 'object.c', line 828

static VALUE
rb_obj_dummy(void)
{
    return Qnil;
}

#method_undefinedObject (private)

Not documented



828
829
830
831
832
# File 'object.c', line 828

static VALUE
rb_obj_dummy(void)
{
    return Qnil;
}

#class_eval(string[, filename [, lineno]]) ⇒ Object #module_eval { ... } ⇒ Object

Evaluates the string or block in the context of mod, except that when a block is given, constant/class variable lookup is not affected. 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

Overloads:

  • #class_eval(string[, filename [, lineno]]) ⇒ Object

    Returns:

  • #module_eval { ... } ⇒ Object

    Yields:

    Returns:



1643
1644
1645
1646
1647
# File 'vm_eval.c', line 1643

VALUE
rb_mod_module_eval(int argc, VALUE *argv, VALUE mod)
{
    return specific_eval(argc, argv, mod, mod);
}

#module_exec(arg...) {|var...| ... } ⇒ Object #class_exec(arg...) {|var...| ... } ⇒ Object

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!

Overloads:

  • #module_exec(arg...) {|var...| ... } ⇒ Object

    Yields:

    • (var...)

    Returns:

  • #class_exec(arg...) {|var...| ... } ⇒ Object

    Yields:

    • (var...)

    Returns:



1669
1670
1671
1672
1673
# File 'vm_eval.c', line 1669

VALUE
rb_mod_module_exec(int argc, VALUE *argv, VALUE mod)
{
    return yield_under(mod, mod, rb_ary_new4(argc, argv));
}

#module_function(symbol, ...) ⇒ self (private)

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 call_one
    one
  end
end
Mod.one     #=> "This is one"
c = Cls.new
c.call_one  #=> "This is one"
module Mod
  def one
    "This is the new one"
  end
end
Mod.one     #=> "This is one"
c.call_one  #=> "This is the new one"

Returns:

  • (self)


1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
# File 'vm_method.c', line 1445

static VALUE
rb_mod_modfunc(int argc, VALUE *argv, VALUE module)
{
    int i;
    ID id;
    const rb_method_entry_t *me;

    if (!RB_TYPE_P(module, T_MODULE)) {
	rb_raise(rb_eTypeError, "module_function must be called for modules");
    }

    secure_visibility(module);
    if (argc == 0) {
	SCOPE_SET(NOEX_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 (;;) {
	    me = search_method(m, id, 0);
	    if (me == 0) {
		me = search_method(rb_cObject, id, 0);
	    }
	    if (UNDEFINED_METHOD_ENTRY_P(me)) {
		rb_print_undef(module, id, 0);
	    }
	    if (me->def->type != VM_METHOD_TYPE_ZSUPER) {
		break; /* normal case: need not to follow 'super' link */
	    }
	    m = RCLASS_SUPER(m);
	    if (!m)
		break;
	}
	rb_method_entry_set(rb_singleton_class(module), id, me, NOEX_PUBLIC);
    }
    return module;
}

#nameString

Returns the name of the module mod. Returns nil for anonymous modules.

Returns:



204
205
206
207
208
209
210
211
212
# File 'variable.c', line 204

VALUE
rb_mod_name(VALUE mod)
{
    int permanent;
    VALUE path = classname(mod, &permanent);

    if (!NIL_P(path)) return rb_str_dup(path);
    return path;
}

#prependself (private)

Invokes Module.prepend_features on each parameter in reverse order.

Returns:

  • (self)


1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
# File 'eval.c', line 1029

static VALUE
rb_mod_prepend(int argc, VALUE *argv, VALUE module)
{
    int i;
    ID id_prepend_features, id_prepended;

    CONST_ID(id_prepend_features, "prepend_features");
    CONST_ID(id_prepended, "prepended");
    for (i = 0; i < argc; i++)
	Check_Type(argv[i], T_MODULE);
    while (argc--) {
	rb_funcall(argv[argc], id_prepend_features, 1, module);
	rb_funcall(argv[argc], id_prepended, 1, module);
    }
    return module;
}

#prepend_features(mod) ⇒ Object (private)

When this module is prepended in another, Ruby calls prepend_features in this module, passing it the receiving module in mod. Ruby's default implementation is to overlay 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#prepend.



1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
# File 'eval.c', line 1006

static VALUE
rb_mod_prepend_features(VALUE module, VALUE prepend)
{
    switch (TYPE(prepend)) {
      case T_CLASS:
      case T_MODULE:
	break;
      default:
	Check_Type(prepend, T_CLASS);
	break;
    }
    rb_prepend_module(prepend, module);

    return module;
}

#prependedObject (private)

Not documented



828
829
830
831
832
# File 'object.c', line 828

static VALUE
rb_obj_dummy(void)
{
    return Qnil;
}

#privateself (private) #private(symbol, ...) ⇒ self (private)

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]

Overloads:

  • #privateself

    Returns:

    • (self)
  • #private(symbol, ...) ⇒ self

    Returns:

    • (self)


1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
# File 'vm_method.c', line 1337

static VALUE
rb_mod_private(int argc, VALUE *argv, VALUE module)
{
    secure_visibility(module);
    if (argc == 0) {
	SCOPE_SET(NOEX_PRIVATE);
    }
    else {
	set_method_visibility(module, argc, argv, NOEX_PRIVATE);
    }
    return module;
}

#private_class_method(symbol, ...) ⇒ Object

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


1380
1381
1382
1383
1384
1385
# File 'vm_method.c', line 1380

static VALUE
rb_mod_private_method(int argc, VALUE *argv, VALUE obj)
{
    set_method_visibility(CLASS_OF(obj), argc, argv, NOEX_PRIVATE);
    return obj;
}

#private_constant(symbol, ...) ⇒ Object

Makes a list of existing constants private.



2263
2264
2265
2266
2267
2268
# File 'variable.c', line 2263

VALUE
rb_mod_private_constant(int argc, VALUE *argv, VALUE obj)
{
    set_const_visibility(obj, argc, argv, CONST_PRIVATE);
    return obj;
}

#private_instance_methods(include_super = true) ⇒ Array

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]

Returns:



1086
1087
1088
1089
1090
# File 'class.c', line 1086

VALUE
rb_class_private_instance_methods(int argc, VALUE *argv, VALUE mod)
{
    return class_instance_method_list(argc, argv, mod, 0, ins_methods_priv_i);
}

#private_method_defined?(symbol) ⇒ Boolean

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

Returns:

  • (Boolean)

Returns:

  • (Boolean)


1046
1047
1048
1049
1050
# File 'vm_method.c', line 1046

static VALUE
rb_mod_private_method_defined(VALUE mod, VALUE mid)
{
    return check_definition(mod, mid, NOEX_PRIVATE);
}

#protectedself (private) #protected(symbol, ...) ⇒ self (private)

With no arguments, sets the default visibility for subsequently defined methods to protected. With arguments, sets the named methods to have protected visibility.

Overloads:

  • #protectedself

    Returns:

    • (self)
  • #protected(symbol, ...) ⇒ self

    Returns:

    • (self)


1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
# File 'vm_method.c', line 1305

static VALUE
rb_mod_protected(int argc, VALUE *argv, VALUE module)
{
    secure_visibility(module);
    if (argc == 0) {
	SCOPE_SET(NOEX_PROTECTED);
    }
    else {
	set_method_visibility(module, argc, argv, NOEX_PROTECTED);
    }
    return module;
}

#protected_instance_methods(include_super = true) ⇒ Array

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.

Returns:



1063
1064
1065
1066
1067
# File 'class.c', line 1063

VALUE
rb_class_protected_instance_methods(int argc, VALUE *argv, VALUE mod)
{
    return class_instance_method_list(argc, argv, mod, 0, ins_methods_prot_i);
}

#protected_method_defined?(symbol) ⇒ Boolean

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

Returns:

  • (Boolean)

Returns:

  • (Boolean)


1078
1079
1080
1081
1082
# File 'vm_method.c', line 1078

static VALUE
rb_mod_protected_method_defined(VALUE mod, VALUE mid)
{
    return check_definition(mod, mid, NOEX_PROTECTED);
}

#publicself (private) #public(symbol, ...) ⇒ self (private)

With no arguments, sets the default visibility for subsequently defined methods to public. With arguments, sets the named methods to have public visibility.

Overloads:

  • #publicself

    Returns:

    • (self)
  • #public(symbol, ...) ⇒ self

    Returns:

    • (self)


1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
# File 'vm_method.c', line 1282

static VALUE
rb_mod_public(int argc, VALUE *argv, VALUE module)
{
    secure_visibility(module);
    if (argc == 0) {
	SCOPE_SET(NOEX_PUBLIC);
    }
    else {
	set_method_visibility(module, argc, argv, NOEX_PUBLIC);
    }
    return module;
}

#public_class_method(symbol, ...) ⇒ Object

Makes a list of existing class methods public.



1357
1358
1359
1360
1361
1362
# File 'vm_method.c', line 1357

static VALUE
rb_mod_public_method(int argc, VALUE *argv, VALUE obj)
{
    set_method_visibility(CLASS_OF(obj), argc, argv, NOEX_PUBLIC);
    return obj;
}

#public_constant(symbol, ...) ⇒ Object

Makes a list of existing constants public.



2277
2278
2279
2280
2281
2282
# File 'variable.c', line 2277

VALUE
rb_mod_public_constant(int argc, VALUE *argv, VALUE obj)
{
    set_const_visibility(obj, argc, argv, CONST_PUBLIC);
    return obj;
}

#public_instance_method(symbol) ⇒ Object

Similar to instance_method, searches public method only.



1311
1312
1313
1314
1315
1316
1317
1318
1319
# File 'proc.c', line 1311

static VALUE
rb_mod_public_instance_method(VALUE mod, VALUE vid)
{
    ID id = rb_check_id(&vid);
    if (!id) {
	rb_method_name_error(mod, vid);
    }
    return mnew(mod, Qundef, id, rb_cUnboundMethod, TRUE);
}

#public_instance_methods(include_super = true) ⇒ Array

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.

Returns:



1101
1102
1103
1104
1105
# File 'class.c', line 1101

VALUE
rb_class_public_instance_methods(int argc, VALUE *argv, VALUE mod)
{
    return class_instance_method_list(argc, argv, mod, 0, ins_methods_pub_i);
}

#public_method_defined?(symbol) ⇒ Boolean

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

Returns:

  • (Boolean)

Returns:

  • (Boolean)


1014
1015
1016
1017
1018
# File 'vm_method.c', line 1014

static VALUE
rb_mod_public_method_defined(VALUE mod, VALUE mid)
{
    return check_definition(mod, mid, NOEX_PUBLIC);
}

#refine(klass) { ... } ⇒ Object (private)

Refine klass in the receiver.

Returns an overlaid module.

Yields:



1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
# File 'eval.c', line 1178

static VALUE
rb_mod_refine(VALUE module, VALUE klass)
{
    VALUE refinement;
    ID id_refinements, id_activated_refinements,
       id_refined_class, id_defined_at;
    VALUE refinements, activated_refinements;
    rb_thread_t *th = GET_THREAD();
    rb_block_t *block = rb_vm_control_frame_block_ptr(th->cfp);

    warn_refinements_once();
    if (!block) {
        rb_raise(rb_eArgError, "no block given");
    }
    if (block->proc) {
        rb_raise(rb_eArgError,
		 "can't pass a Proc as a block to Module#refine");
    }
    Check_Type(klass, T_CLASS);
    CONST_ID(id_refinements, "__refinements__");
    refinements = rb_attr_get(module, id_refinements);
    if (NIL_P(refinements)) {
	refinements = hidden_identity_hash_new();
	rb_ivar_set(module, id_refinements, refinements);
    }
    CONST_ID(id_activated_refinements, "__activated_refinements__");
    activated_refinements = rb_attr_get(module, id_activated_refinements);
    if (NIL_P(activated_refinements)) {
	activated_refinements = hidden_identity_hash_new();
	rb_ivar_set(module, id_activated_refinements,
		    activated_refinements);
    }
    refinement = rb_hash_lookup(refinements, klass);
    if (NIL_P(refinement)) {
	refinement = rb_module_new();
	RCLASS_SUPER(refinement) = klass;
	FL_SET(refinement, RMODULE_IS_REFINEMENT);
	CONST_ID(id_refined_class, "__refined_class__");
	rb_ivar_set(refinement, id_refined_class, klass);
	CONST_ID(id_defined_at, "__defined_at__");
	rb_ivar_set(refinement, id_defined_at, module);
	rb_hash_aset(refinements, klass, refinement);
	add_activated_refinement(activated_refinements, klass, refinement);
    }
    rb_yield_refine_block(refinement, activated_refinements);
    return refinement;
}

#remove_class_variable(sym) ⇒ Object

Removes the definition of the sym, returning that constant's value.

class Dummy
  @@var = 99
  puts @@var
  remove_class_variable(:@@var)
  p(defined? @@var)
end

produces:

99
nil

Returns:



2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
# File 'variable.c', line 2543

VALUE
rb_mod_remove_cvar(VALUE mod, VALUE name)
{
    const ID id = rb_check_id(&name);
    st_data_t val, n = id;

    if (!id) {
	if (rb_is_class_name(name)) {
	    rb_name_error_str(name, "class variable %"PRIsVALUE" not defined for %"PRIsVALUE"",
			      name, rb_class_name(mod));
	}
	else {
	    rb_name_error_str(name, "wrong class variable name %"PRIsVALUE"", QUOTE(name));
	}
    }
    if (!rb_is_class_id(id)) {
	rb_name_error(id, "wrong class variable name %"PRIsVALUE"", QUOTE_ID(id));
    }
    if (!OBJ_UNTRUSTED(mod) && rb_safe_level() >= 4)
	rb_raise(rb_eSecurityError, "Insecure: can't remove class variable");
    rb_check_frozen(mod);
    if (RCLASS_IV_TBL(mod) && st_delete(RCLASS_IV_TBL(mod), &n, &val)) {
	return (VALUE)val;
    }
    if (rb_cvar_defined(mod, id)) {
	rb_name_error(id, "cannot remove %"PRIsVALUE" for %"PRIsVALUE"",
		 QUOTE_ID(id), rb_class_name(mod));
    }
    rb_name_error(id, "class variable %"PRIsVALUE" not defined for %"PRIsVALUE"",
		  QUOTE_ID(id), rb_class_name(mod));

    UNREACHABLE;
}

#remove_const(sym) ⇒ Object (private)

Removes the definition of the given constant, returning that constant's previous value. If that constant referred to a module, this will not change that module's name and can lead to confusion.

Returns:



1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
# File 'variable.c', line 1910

VALUE
rb_mod_remove_const(VALUE mod, VALUE name)
{
    const ID id = rb_check_id(&name);

    if (!id) {
	if (rb_is_const_name(name)) {
	    rb_name_error_str(name, "constant %"PRIsVALUE"::%"PRIsVALUE" not defined",
			      rb_class_name(mod), name);
	}
	else {
	    rb_name_error_str(name, "`%"PRIsVALUE"' is not allowed as a constant name",
			      QUOTE(name));
	}
    }
    if (!rb_is_const_id(id)) {
	rb_name_error(id, "`%"PRIsVALUE"' is not allowed as a constant name",
		      QUOTE_ID(id));
    }
    return rb_const_remove(mod, id);
}

#remove_method(symbol) ⇒ self (private)

Removes the method identified by symbol from the current class. For an example, see Module.undef_method.

Returns:

  • (self)


700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
# File 'vm_method.c', line 700

static VALUE
rb_mod_remove_method(int argc, VALUE *argv, VALUE mod)
{
    int i;

    for (i = 0; i < argc; i++) {
	VALUE v = argv[i];
	ID id = rb_check_id(&v);
	if (!id) {
	    rb_name_error_str(v, "method `%s' not defined in %s",
			      RSTRING_PTR(v), rb_class2name(mod));
	}
	remove_method(mod, id);
    }
    return mod;
}

#to_sString Also known as: inspect

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.

Returns:



1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
# File 'object.c', line 1369

static VALUE
rb_mod_to_s(VALUE klass)
{
    ID id_defined_at;
    VALUE refined_class, defined_at;

    if (FL_TEST(klass, FL_SINGLETON)) {
	VALUE s = rb_usascii_str_new2("#<Class:");
	VALUE v = rb_iv_get(klass, "__attached__");

	if (CLASS_OR_MODULE_P(v)) {
	    rb_str_append(s, rb_inspect(v));
	}
	else {
	    rb_str_append(s, rb_any_to_s(v));
	}
	rb_str_cat2(s, ">");

	return s;
    }
    refined_class = rb_refinement_module_get_refined_class(klass);
    if (!NIL_P(refined_class)) {
	VALUE s = rb_usascii_str_new2("#<refinement:");

	rb_str_concat(s, rb_inspect(refined_class));
	rb_str_cat2(s, "@");
	CONST_ID(id_defined_at, "__defined_at__");
	defined_at = rb_attr_get(klass, id_defined_at);
	rb_str_concat(s, rb_inspect(defined_at));
	rb_str_cat2(s, ">");
	return s;
    }
    return rb_str_dup(rb_class_name(klass));
}

#undef_method(symbol) ⇒ self (private)

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)

Returns:

  • (self)


920
921
922
923
924
925
926
927
928
929
930
931
932
933
# File 'vm_method.c', line 920

static VALUE
rb_mod_undef_method(int argc, VALUE *argv, VALUE mod)
{
    int i;
    for (i = 0; i < argc; i++) {
	VALUE v = argv[i];
	ID id = rb_check_id(&v);
	if (!id) {
	    rb_method_name_error(mod, v);
	}
	rb_undef(mod, id);
    }
    return mod;
}

#usedObject (private)

Not documented



828
829
830
831
832
# File 'object.c', line 828

static VALUE
rb_obj_dummy(void)
{
    return Qnil;
}