Programming Ruby: The Pragmatic Programmer's Guide

# Programming Ruby ### The Pragmatic Programmer's Guide
Previous < | Contents ^ | Next >

class Module |
Parent: | Object
Version: | 1.6

### Index:

constants nesting new <, <=, >, >= <=> === ancestors class_eval class_variables clone const_defined? const_get const_set constants included_modules instance_methods method_defined? module_eval name private_class_method private_instance_methods protected_instance_methods public_class_method public_instance_methods alias_method append_features attr attr_accessor attr_reader attr_writer extend_object include method_added module_function private protected public remove_const remove_method undef_method

Subclasses: Class

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` on page 346.

In the descriptions that follow, the parameter aSymbol 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.type` | » | `Module`
`Mod.constants` | » | `["CONST", "E", "PI"]`
`Mod.instance_methods` | » | `["meth"]`

class methods
constants | Module.constants -> anArray
|  | Returns an array of the names of all constants defined in the system. This list includes the names of all modules and classes.
    p Module.constants.sort[1..5]
produces:
    ["ARGV", "ArgumentError", "Array", "Bignum", "Binding"]
nesting | Module.nesting -> anArray
|  | 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"`
new | Module.new -> aModule
|  | Creates a new anonymous module.

instance methods
<, <=, >, >= | mod `relop` aModule -> `true` or `false`
|  | Hierarchy Query---One module is considered greater than another if it is included in (or is a parent class of) the other module. The other operators are defined accordingly. If there is no relationship between the modules, returns false for all operators.
`module Mixin`
`end`
``
`module Parent`
`include Mixin`
`end`
``
`module Unrelated`
`end`
``
`Parent > Mixin` | » | `false`
`Parent < Mixin` | » | `true`
`Parent <= Parent` | » | `true`
`Parent < Unrelated` | » | `false`
`Parent > Unrelated` | » | `false`
<=> | mod <=> aModule -> -1, 0, +1
|  | Comparison---Returns -1 if mod includes aModule, 0 if mod is the same as aModule, and +1 if mod is included by aModule or if mod has no relationship with aModule.
=== | mod === anObject -> `true` or `false`
|  | Case Equality---Returns `true` if anObject is an instance of mod or one of mod's descendents. Of limited use for modules, but can be used in `case` statements to classify objects by class.
ancestors | mod.ancestors -> anArray
|  | 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]`
class_eval | mod.class_eval( aString ) -> anObject mod.class_eval {| | block } -> anObject
|  | Synonym for `Module.module_eval`.
class_variables | mod.class_variables -> anArray
|  | Returns an array of the names of class variables in mod and the ancestors of mod.
`class One`
`@@var1 = 1`
`end`
`class Two < One`
`@@var2 = 2`
`end`
`One.class_variables` | » | `["@@var1"]`
`Two.class_variables` | » | `["@@var2", "@@var1"]`
clone | mod.clone -> aModule
|  | Creates a new copy of a module.
`m = Math.clone` | » | `Math`
`m.constants` | » | `["E", "PI"]`
`m == Math` | » | `false`
const_defined? | mod.const_defined?( aSymbol ) -> `true` or `false`
|  | Returns `true` if a constant with the given name is defined by mod.
`Math.const_defined? "PI"` | » | `true`
const_get | mod.const_get( aSymbol ) -> anObject
|  | Returns the value of the named constant in mod.
`Math.const_get :PI` | » | `3.141592654`
const_set | mod.const_set( aSymbol, anObject ) -> anObject
|  | 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.142857143`
`Math::HIGH_SCHOOL_PI - Math::PI` | » | `0.001264489267`
constants | mod.constants -> anArray
|  | 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).
included_modules | mod.included_modules -> anArray
|  | Returns the list of modules included in mod.
`module Mixin`
`end`
``
`module Outer`
`include Mixin`
`end`
``
`Mixin.included_modules` | » | `[]`
`Outer.included_modules` | » | `[Mixin]`
instance_methods | mod.instance_methods( includeSuper=`false` ) -> anArray
|  | Returns an array containing the names of public instance methods in the receiver. For a module, these are the public methods; for a class, they are the instance (not singleton) methods. With no argument, or with an argument that is `false`, the instance methods in mod are returned, otherwise the methods in mod and mod's superclasses are returned.
    module A
      def method1()  end
    end
    class B
      def method2()  end
    end
    class C < B
      def method3()  end
    end
`A.instance_methods` | » | `["method1"]`
`B.instance_methods` | » | `["method2"]`
`C.instance_methods` | » | `["method3"]`
`C.instance_methods(true).length` | » | `39`
method_defined? | mod.method_defined?( aSymbol ) -> `true` or `false`
|  | Returns `true` if the named method is defined by mod (or its included modules and, if mod is a class, its ancestors).
`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`
module_eval | mod.module_eval( aString ) -> anObject mod.module_eval {| | block } -> anObject
|  | 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.
`class Thing`
`end`
`a = %q{def hello() "Hello there!" end}`
`Thing.module_eval(a)` | » | `nil`
`Thing.new.hello()` | » | `"Hello there!"`
name | mod.name -> aString
|  | Returns the name of the module mod.
private_class_method | mod.private_class_method( [ aSymbol ]+ ) -> `nil`
|  | 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
private_instance_methods | mod.private_instance_methods( includeSuper=`false` ) -> anArray
|  | 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"]`
protected_instance_methods | mod.protected_instance_methods( includeSuper=`false` ) -> anArray
|  | 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.
public_class_method | mod.public_class_method( [ aSymbol ]+ ) -> `nil`
|  | Makes a list of existing class methods public.
public_instance_methods | mod.public_instance_methods( includeSuper=`false` ) -> anArray
|  | 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.

private methods
alias_method | alias_method( newID, oldID ) -> mod
|  | Makes newID a new copy of the method oldID. This can be used to retain access to methods that are overridden.
    module Mod
      alias_method :origExit, :exit
      def exit(code=0)
        print "Exiting with code #{code}\n"
        origExit(code)
      end
    end
    include Mod
    exit(99)
produces:
    Exiting with code 99
append_features | append_features( aModule ) -> mod
|  | When this module is included in another, Ruby calls `append_features` in this module, passing it the receiving module in aModule. Ruby's default implementation is to add the constants, methods, and module variables of this module to aModule if this module has not already been added to aModule or one of its ancestors. See also `Module#include` on page 345.
attr | attr( aSymbol, writable=`false` ) -> `nil`
|  | Defines a named attribute for this module, where the name is aSymbol. `id2name`, creating an instance variable (`@name`) and a corresponding access method to read it. If the optional writable argument is `true`, also creates a method called `name=` to set the attribute.
    module Mod
      attr  :size, true
    end
is equivalent to:
    module Mod
      def size
        @size
      end
      def size=(val)
        @size = val
      end
    end
attr_accessor | attr_accessor( [ aSymbol ]+ ) -> `nil`
|  | Equivalent to calling ```attr` aSymbol `, true`'' on each aSymbol in turn.
`module Mod`
`attr_accessor(:one, :two)`
`end`
`Mod.instance_methods.sort` | » | `["one", "one=", "two", "two="]`
attr_reader | attr_reader( [ aSymbol ]+ ) -> `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.
attr_writer | attr_writer( [ aSymbol ]+ ) -> `nil`
|  | Creates an accessor method to allow assignment to the attribute aSymbol `.id2name`.
extend_object | extend_object( anObject ) -> anObject
|  | 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
          print "Can't add Picky to a String\n"
        else
          print "Picky added to ", o.type, "\n"
          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
include | include( [ aModule ]+ ) -> mod
|  | Invokes `Module.append_features` (documented on page 344) on each parameter in turn.
method_added | method_added( aSymbol )
|  | Invoked as a callback whenever a method is added to the receiver.
    module Chatty
      def Chatty.method_added(id)
        print "Adding ", id.id2name, "\n"
      end
      def one()   end
    end
    module Chatty
      def two()   end
    end
produces:
    Adding one
    Adding two
module_function | module_function( [ aSymbol ]* ) -> mod
|  | Creates module functions for the named methods. These functions may be called with the module as a receiver, and also become available as instance methods to classes that mix in the module. Module functions are copies of the original, and so may be changed independently. The instance-method versions are made private. If used with no arguments, subsequently defined methods become module functions.
`module Mod`
`def one`
`"This is one"`
`end`
`module_function :one`
`end`
`class Cls`
`include Mod`
`def callOne`
`one`
`end`
`end`
`Mod.one` | » | `"This is one"`
`c = Cls.new`
`c.callOne` | » | `"This is one"`
`module Mod`
`def one`
`"This is the new one"`
`end`
`end`
`Mod.one` | » | `"This is one"`
`c.callOne` | » | `"This is the new one"`
private | private( [ aSymbol ]* ) -> mod
|  | With no arguments, sets the default visibility for subsequently defined methods to private. With arguments, sets the named methods to have private visibility. See Access Control starting on page 233.
`module Mod`
`def a() end`
`def b() end`
`private`
`def c() end`
`private :a`
`end`
`Mod.private_instance_methods` | » | `["a", "c"]`
protected | protected( [ aSymbol ]* ) -> mod
|  | With no arguments, sets the default visibility for subsequently defined methods to protected. With arguments, sets the named methods to have protected visibility. See Access Control starting on page 233.
public | public( [ aSymbol ]* ) -> mod
|  | With no arguments, sets the default visibility for subsequently defined methods to public. With arguments, sets the named methods to have public visibility. See Access Control starting on page 233.
remove_const | remove_const( aSymbol ) -> anObject
|  | Removes the definition of the given constant, returning that constant's value. Predefined classes and singleton objects (such as true) cannot be removed.
remove_method | remove_method( aSymbol ) -> mod
|  | Removes the method identified by aSymbol from the current class. For an example, see `Module.undef_method`.
undef_method | undef_method( aSymbol ) -> mod
|  | 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
        print "In parent\n"
      end
    end
    class Child < Parent
      def hello
        print "In child\n"
      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:0x401b5928> (NameError)

Previous < | Contents ^ | Next >

Extracted from the book "Programming Ruby - The Pragmatic Programmer's Guide"
Copyright © 2001 by Addison Wesley Longman, Inc. This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, v1.0 or later (the latest version is presently available at http://www.opencontent.org/openpub/)).

Distribution of substantively modified versions of this document is prohibited without the explicit permission of the copyright holder.

Distribution of the work or derivative of the work in any standard (paper) book form is prohibited unless prior permission is obtained from the copyright holder.