Class: Module

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

Overview

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 sym 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          #=> [:CONST, :PI, :E]
Mod.instance_methods   #=> [:meth]

Direct Known Subclasses

Class

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#newObject

Returns a new BasicObject.



# File 'object.c'

/*
 *  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"
 *
 *  Assign the module to a constant (name starting uppercase) if you
 *  want to treat it like a regular module.
 */

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

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:



# File 'eval.c'

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);
}

.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:



# File 'eval.c'

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);
}

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)


# File 'object.c'

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)


# File 'object.c'

VALUE
rb_class_inherited_p(VALUE mod, VALUE 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");
}

#<=>(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)


# File 'object.c'

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

if (mod == arg) return INT2FIX(0);
switch (TYPE(arg)) {
  case T_MODULE:
  case T_CLASS:
break;
  default:
return Qnil;
}

#==(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: 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

Overloads:

  • #==(other) ⇒ Boolean

    Returns:

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

    Returns:

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

    Returns:

    • (Boolean)


# File 'object.c'

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)


# File 'object.c'

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)


# File 'object.c'

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)


# File 'object.c'

static VALUE
rb_mod_ge(VALUE mod, VALUE arg)
{
switch (TYPE(arg)) {
  case T_MODULE:
  case T_CLASS:
break;
  default:
rb_raise(rb_eTypeError, "compared with non class/module");
}

#alias_method(new_name, old_name) ⇒ Module

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:



# File 'vm_method.c'

static VALUE
rb_mod_alias_method(VALUE mod, VALUE newname, VALUE oldname)
{
    rb_alias(mod, rb_to_id(newname), rb_to_id(oldname));
    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:



# File 'object.c'

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);
}

#append_features(mod) ⇒ Object

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.



# File 'eval.c'

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;
}

#attrObject

#attr_accessor(symbol, ...) ⇒ nil

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)


# File 'object.c'

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);
}

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

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)


# File 'object.c'

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);
}

#attr_writer(symbol, ...) ⇒ nil

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

Returns:

  • (nil)


# File 'object.c'

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);
}

#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)


# File 'load.c'

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:



# File 'load.c'

static VALUE
rb_mod_autoload_p(VALUE mod, VALUE sym)
{
    return rb_autoload_p(mod, rb_to_id(sym));
}

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

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

Overloads:

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

    Returns:

  • #module_eval { ... } ⇒ Object

    Yields:

    Returns:



# File 'vm_eval.c'

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:



# File 'vm_eval.c'

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)


# File 'object.c'

static VALUE
rb_mod_cvar_defined(VALUE obj, VALUE 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));
}

#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:



# File 'object.c'

static VALUE
rb_mod_cvar_get(VALUE obj, VALUE 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));
}

#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:



# File 'object.c'

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, "`%s' is not allowed as a class variable name", rb_id2name(id));
}

#class_variablesArray

Returns an array of the names of class variables in mod.

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

Returns:



# File 'object.c'

VALUE
rb_mod_class_variables(VALUE obj)
{
VALUE ary = rb_ary_new();

if (RCLASS_IV_TBL(obj)) {
	st_foreach_safe(RCLASS_IV_TBL(obj), cv_i, ary);
}

#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)


# File 'object.c'

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;
}

#const_get(sym, 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

Returns:



# File 'object.c'

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

if (argc == 1) {
name = argv[0];
recur = Qtrue;
}

#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:



# File 'object.c'

VALUE
rb_mod_const_missing(VALUE klass, VALUE name)
{
    rb_frame_pop(); /* pop frame for "const_missing" */
    uninitialized_constant(klass, rb_to_id(name));
    return Qnil;		/* not reached */
}

#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:



# File 'object.c'

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 %s", rb_id2name(id));
}

#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 all parameter is set to false.

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

Also see Module::const_defined?.

Returns:



# File 'object.c'

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

if (argc == 0) {
	inherit = Qtrue;
}

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

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:



# File 'proc.c'

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();
}

#extend_object(obj) ⇒ Object

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:



# File 'eval.c'

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

#extendedObject

Not documented



# File 'object.c'

static VALUE
rb_obj_dummy(void)
{
    return Qnil;
}

#freezeObject

Prevents further modifications to mod.

This method returns self.



# File 'object.c'

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

#includeModule

Invokes Module.append_features on each parameter in reverse order.

Returns:



# File 'eval.c'

static VALUE
rb_mod_include(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);
}

#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)


# File 'object.c'

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;
}

#included(othermod) ⇒ Object

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


# File 'object.c'

/*
 * Not documented
 */

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:



# File 'object.c'

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);
}

#initialize_copyObject

:nodoc:



# File 'object.c'

VALUE
rb_mod_init_copy(VALUE clone, VALUE 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);
}

#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!


# File 'proc.c'

static VALUE
rb_mod_instance_method(VALUE mod, VALUE vid)
{
    return mnew(mod, Qundef, rb_to_id(vid), 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:



# File 'object.c'

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

#method_added(method_name) ⇒ Object

Invoked as a callback whenever an instance method is added to the receiver.

module Chatty
  def self.method_added(method_name)
    puts "Adding #{method_name.inspect}"
  end
  def self.some_class_method() end
  def some_instance_method() end
end

produces:

Adding :some_instance_method


# File 'object.c'

/*
 * Not documented
 */

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)


# File 'vm_method.c'

static VALUE
rb_mod_method_defined(VALUE mod, VALUE mid)
{
if (!rb_method_boundp(mod, rb_to_id(mid), 1)) {
return Qfalse;
}

#method_removed(method_name) ⇒ Object

Invoked as a callback whenever an instance method is removed from the receiver.

module Chatty
  def self.method_removed(method_name)
    puts "Removing #{method_name.inspect}"
  end
  def self.some_class_method() end
  def some_instance_method() end
  class << self
    remove_method :some_class_method
  end
  remove_method :some_instance_method
end

produces:

Removing :some_instance_method


# File 'object.c'

/*
 * Not documented
 */

static VALUE
rb_obj_dummy(void)
{
    return Qnil;
}

#method_undefinedObject

Not documented



# File 'object.c'

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. 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:



# File 'vm_eval.c'

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:



# File 'vm_eval.c'

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

#module_function(symbol, ...) ⇒ Module

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:



# File 'vm_method.c'

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

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

#nameString

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

Returns:



# File 'object.c'

VALUE
rb_mod_name(VALUE mod)
{
    VALUE path = classname(mod);

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

#privateModule #private(symbol, ...) ⇒ 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]

Overloads:



# File 'vm_method.c'

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

#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


# File 'vm_method.c'

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_constantObject

#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:



# File 'object.c'

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)


# File 'vm_method.c'

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

#protectedModule #protected(symbol, ...) ⇒ Module

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

Overloads:



# File 'vm_method.c'

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

#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:



# File 'object.c'

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)


# File 'vm_method.c'

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

#publicModule #public(symbol, ...) ⇒ Module

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

Overloads:



# File 'vm_method.c'

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

#public_class_method(symbol, ...) ⇒ Object

Makes a list of existing class methods public.



# File 'vm_method.c'

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_constantObject

#public_instance_method(symbol) ⇒ Object

Similar to instance_method, searches public method only.



# File 'proc.c'

static VALUE
rb_mod_public_instance_method(VALUE mod, VALUE vid)
{
    return mnew(mod, Qundef, rb_to_id(vid), 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:



# File 'object.c'

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)


# File 'vm_method.c'

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

#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:



# File 'object.c'

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

if (!rb_is_class_id(id)) {
	rb_name_error(id, "wrong class variable name %s", rb_id2name(id));
}

#remove_const(sym) ⇒ Object

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:



# File 'object.c'

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

if (!rb_is_const_id(id)) {
	rb_name_error(id, "`%s' is not allowed as a constant name", rb_id2name(id));
}

#remove_method(symbol) ⇒ Module

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

Returns:



# File 'vm_method.c'

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

for (i = 0; i < argc; i++) {
remove_method(mod, rb_to_id(argv[i]));
}

#to_sString

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:



# File 'object.c'

static VALUE
rb_mod_to_s(VALUE klass)
{
if (FL_TEST(klass, FL_SINGLETON)) {
VALUE s = rb_usascii_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;
}

#undef_method(symbol) ⇒ Module

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:



# File 'vm_method.c'

static VALUE
rb_mod_undef_method(int argc, VALUE *argv, VALUE mod)
{
int i;
for (i = 0; i < argc; i++) {
rb_undef(mod, rb_to_id(argv[i]));
}