Class: Module

Inherits:
NSObject show all

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)

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.

Overloads:

  • + constants

    Returns:

  • + constants

    Returns:

+ (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"

Returns:

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

Returns:

  • (true, false, nil)

- (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

Returns:

  • (true, false, nil)

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

Returns:

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

- (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

Overloads:

  • - ==

    Returns:

    • (Boolean)
  • - equal?

    Returns:

    • (Boolean)
  • - eql?

    Returns:

    • (Boolean)

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

Returns:

  • (Boolean)

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

Returns:

  • (true, false, nil)

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

Returns:

  • (true, false, nil)

- (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]

Returns:

- (nil) autoload

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)

- (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"

Returns:

Returns:

  • (Boolean)

- (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

Overloads:

  • - class_eval

    Returns:

  • - module_eval { ... }

    Yields:

    Returns:

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

Overloads:

  • - module_exec {|var...| ... }

    Yields:

    • (var...)

    Returns:

  • - class_exec {|var...| ... }

    Yields:

    • (var...)

    Returns:

- (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

Returns:

  • (Boolean)

Returns:

  • (Boolean)

- (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

Returns:

- (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

Returns:

- (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]

Returns:

- (Boolean) const_defined?(sym, inherit = true)

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)

- (Object) const_get(sym, inherit = true)

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:

- (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

Returns:

- (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

Returns:

- (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?.

Returns:

- (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

Returns:

  • (Boolean)

Returns:

  • (Boolean)

- (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]

Returns:

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

Returns:

- (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

Returns:

  • (Boolean)

Returns:

  • (Boolean)

- (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

Overloads:

  • - class_eval

    Returns:

  • - module_eval { ... }

    Yields:

    Returns:

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

Overloads:

  • - module_exec {|var...| ... }

    Yields:

    • (var...)

    Returns:

  • - class_exec {|var...| ... }

    Yields:

    • (var...)

    Returns:

- (String) name

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

Returns:

- (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

Returns:

  • (Boolean)

Returns:

  • (Boolean)

- (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

Returns:

  • (Boolean)

Returns:

  • (Boolean)

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

Returns:

- (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

Returns:

  • (Boolean)

Returns:

  • (Boolean)

- (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

Returns:

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

Returns: