Class: Module
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 Method Summary (collapse)
- + alloc
-
+ constants
In the first form, returns an array of the names of all constants accessible from the point of call.
-
+ nesting
Returns the list of Modules nested at the point of call.
Instance Method Summary (collapse)
-
- <
Returns true if mod is a subclass of other.
-
- <=
Returns true if mod is a subclass of other or is the same as other.
-
- <=>
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.
-
- ==
Equality---At the Object level, == returns true only if obj and other are the same object.
-
- ===
Case Equality---Returns true if anObject is an instance of mod or one of mod's descendants.
-
- >
Returns true if mod is an ancestor of other.
-
- >=
Returns true if mod is an ancestor of other, or the two modules are the same.
-
- __ancestors__
:nodoc:.
-
- __properties__
:nodoc:.
-
- ancestors
Returns a list of modules included in mod (including mod itself).
- - autoload
-
- autoload?
Returns filename to be loaded if name is registered as autoload in the namespace of mod.
-
- class_eval
Evaluates the string or block in the context of mod.
-
- class_exec
Evaluates the given block in the context of the class/module.
-
- class_variable_defined?
Returns true if the given class variable is defined in obj.
-
- class_variable_get
Returns the value of the given class variable (or throws a NameError exception).
-
- class_variable_set
Sets the class variable names by symbol to object.
-
- class_variables
Returns an array of the names of class variables in mod.
- - const_defined?
- - const_get
-
- const_missing
Invoked when a reference is made to an undefined constant in mod.
-
- const_set
Sets the named constant to the given object, returning that object.
-
- constants
Returns an array of the names of the constants accessible in mod.
-
- freeze
Prevents further modifications to mod.
-
- include?
Returns true if module is included in mod or one of mod's ancestors.
-
- included_modules
Returns the list of modules included in mod.
-
- initialize_copy
:nodoc:.
-
- instance_method
Returns an UnboundMethod representing the given instance method in mod.
- - instance_methods
-
- method_defined?
Returns true if the named method is defined by mod (or its included modules and, if mod is a class, its ancestors).
-
- module_eval
Evaluates the string or block in the context of mod.
-
- module_exec
Evaluates the given block in the context of the class/module.
-
- name
Returns the name of the module mod.
-
- private_class_method
Makes existing class methods private.
- - private_instance_methods
-
- private_method_defined?
Returns true if the named private method is defined by _ mod_ (or its included modules and, if mod is a class, its ancestors).
- - protected_instance_methods
-
- protected_method_defined?
Returns true if the named protected method is defined by mod (or its included modules and, if mod is a class, its ancestors).
-
- public_class_method
Makes a list of existing class methods public.
-
- public_instance_method
Similar to instance_method, searches public method only.
- - public_instance_methods
-
- public_method_defined?
Returns true if the named public method is defined by mod (or its included modules and, if mod is a class, its ancestors).
-
- remove_class_variable
Removes the definition of the sym, returning that constant's value.
-
- to_s
Return a string representing this module or class.
Methods inherited from NSObject
#!, #!=, #!~, #=~, #Rational, #__callee__, #__method__, #__send__, #__type__, `, allocWithZone:, #autoContentAccessingProxy, autoload, autoload?, autorelease_pool, #awakeAfterUsingCoder:, binding, block_given?, caller, cancelPreviousPerformRequestsWithTarget:, cancelPreviousPerformRequestsWithTarget:selector:object:, catch, class, classFallbacksForKeyedArchiver, #classForCoder, #classForKeyedArchiver, classForKeyedUnarchiver, #clone, conformsToProtocol:, #copy, copyWithZone:, #dealloc, #define_singleton_method, description, display, #doesNotRecognizeSelector:, #dup, #enum_for, #eql?, #equal?, #extend, fail, #finalize, format, #forwardInvocation:, #forwardingTargetForSelector:, framework, #frozen?, getpass, gets, global_variables, #init, initialize, #initialize_clone, #initialize_dup, #inspect, instanceMethodForSelector:, instanceMethodSignatureForSelector:, #instance_eval, #instance_exec, #instance_of?, #instance_variable_defined?, #instance_variable_get, #instance_variable_set, #instance_variables, instancesRespondToSelector:, isSubclassOfClass:, #is_a?, iterator?, #kind_of?, lambda, load, load_bridge_support_file, load_plist, local_variables, loop, #method, #methodForSelector:, #methodSignatureForSelector:, #methods, #mutableCopy, mutableCopyWithZone:, new, #nil?, open, p, #performSelector:onThread:withObject:waitUntilDone:, #performSelector:onThread:withObject:waitUntilDone:modes:, #performSelector:withObject:afterDelay:, #performSelector:withObject:afterDelay:inModes:, #performSelectorInBackground:withObject:, #performSelectorOnMainThread:withObject:waitUntilDone:, #performSelectorOnMainThread:withObject:waitUntilDone:modes:, print, printf, #private_methods, proc, #protected_methods, #public_method, #public_methods, #public_send, putc, puts, raise, rand, readline, readlines, #replacementObjectForCoder:, #replacementObjectForKeyedArchiver:, require, resolveClassMethod:, resolveInstanceMethod:, #respond_to?, #respond_to_missing?, select, #send, setVersion:, #singleton_methods, sprintf, srand, superclass, #taint, #tainted?, #tap, test, throw, #to_plist, trace_var, trap, #trust, #untaint, untrace_var, #untrust, #untrusted?, version
Constructor Details
This class inherits a constructor from NSObject
Dynamic Method Handling
This class handles dynamic methods through the method_missing method in the class NSObject
Class Method Details
+ (Object) alloc
+ (Array) constants + (Array) constants(inherited)
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.
+ (Array) nesting
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"
Instance Method Details
- (true, ...) <(other)
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
- (true, ...) <=(other)
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
- (-1, ...) <=>(other_mod)
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.
- (Boolean) ==(other) - (Boolean) equal?(other) - (Boolean) eql?(other)
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
- (Boolean) ===(obj)
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.
- (true, ...) >(other)
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 AA").
- (true, ...) >=(other)
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 AA").
- (Object) __ancestors__
:nodoc:
- (Object) __properties__
:nodoc:
- (Array) ancestors
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]
- (nil) autoload
- (String?) autoload?(name)
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"
- (Object) class_eval(string[, filename [, lineno]]) - (Object) module_eval { ... }
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
- (Object) module_exec(arg...) {|var...| ... } - (Object) class_exec(arg...) {|var...| ... }
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!
- (Boolean) class_variable_defined?(symbol)
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
- (Object) class_variable_get(symbol)
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
- (Object) class_variable_set(symbol, obj)
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
- (Array) class_variables
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]
- (Boolean) const_defined?(sym, inherit = true)
- (Object) const_get(sym, inherit = true)
- (Object) const_missing(sym)
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
- (Object) const_set(sym, obj)
Sets the named constant to the given object, returning that object. Creates a new constant if no constant with the given name previously existed.
Math.const_set("HIGH_SCHOOL_PI", 22.0/7.0) #=> 3.14285714285714
Math::HIGH_SCHOOL_PI - Math::PI #=> 0.00126448926734968
- (Array) constants(inherit = true)
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?.
- (Object) freeze
Prevents further modifications to mod.
This method returns self.
- (Boolean) include?
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
- (Array) included_modules
Returns the list of modules included in mod.
module Mixin
end
module Outer
include Mixin
end
Mixin.included_modules #=> []
Outer.included_modules #=> [Mixin]
- (Object) initialize_copy
:nodoc:
- (UnboundMethod) instance_method(symbol)
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!
- (Object) instance_methods
- (Boolean) method_defined?(symbol)
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
- (Object) class_eval(string[, filename [, lineno]]) - (Object) module_eval { ... }
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
- (Object) module_exec(arg...) {|var...| ... } - (Object) class_exec(arg...) {|var...| ... }
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!
- (String) name
Returns the name of the module mod. Returns nil for anonymous modules.
- (Object) private_class_method(symbol, ...)
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
- (Object) private_instance_methods
- (Boolean) private_method_defined?(symbol)
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
- (Object) protected_instance_methods
- (Boolean) protected_method_defined?(symbol)
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
- (Object) public_class_method(symbol, ...)
Makes a list of existing class methods public.
- (UnboundMethod) public_instance_method(symbol)
Similar to instance_method, searches public method only.
- (Object) public_instance_methods
- (Boolean) public_method_defined?(symbol)
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
- (Object) remove_class_variable(sym)
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
- (String) to_s
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.