Programming Ruby
The Pragmatic Programmer's Guide
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
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"]
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
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.
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.
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
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
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).
Returns the list of modules included in
mod.
module Mixin
end
module Outer
include Mixin
end
Mixin.included_modules
サ
[]
Outer.included_modules
サ
[Mixin]
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
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!"
Returns the name of the module
mod.
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
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 a list of the protected instance methods defined in
mod.
If the optional parameter is not
false, the methods
of any ancestors are included.
Makes a list of existing class methods public.
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
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:
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
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="]
Creates instance variables and corresponding methods that
return the value of each instance variable.
Equivalent to calling ``
attr
:name'' on each name
in turn.
Creates an accessor method to allow assignment to the attribute
aSymbol
.id2name.
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.
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:
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"]
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.
Removes the definition of the given constant, returning that
constant's value. Predefined classes and singleton objects (such
as
true) cannot be removed.
Removes the method identified by
aSymbol
from the current class.
For an example, see
Module.undef_method.
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)
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.