Ruby/Справочник/Module

Материал из Викиучебника — открытых книг для открытого мира
Перейти к навигации Перейти к поиску

Класс Module[править]

Module является коллекцией из методов и констант. Методы в модуле могут быть методами экземпляра или методами модуля. Метод экземпляра появляется как метод в классе, когда модуль подключен директивой include, методы модуля не выполняются. Напротив, методы модуля могут быть вызваны без создания инкапсулирующего объекта, в то время как методы экземпляра не могут. (См. Module#module_function)

В описании ниже, под параметром syml будем понимать символ, который является строкой в кавычках или объектом класса Symbol (таким, как, например, :name).

  module Mod
    include Math
    CONST = 1
    def meth
      #  ...
    end
  end
  Mod.class              #=> Module
  Mod.constants          #=> ["E", "PI", "CONST"]
  Mod.instance_methods   #=> ["meth"]

Extends the module object with module and instance accessors for class attributes, just like the native attr* accessors for instance attributes.


Also, modules included into Object need to be scanned and have their instance methods removed from blank slate. In theory, modules included into Kernel would have to be removed as well, but a "feature" of Ruby prevents late includes into modules from being exposed in the first place.


Методы класса

constants, nesting, new

Методы объекта

<=>, <=, <, ===, ==, >=, >, alias_method, ancestors, append_features, attr_accessor, attr_reader, attr_writer, attr, autoload?, autoload, class_eval, class_variable_get, class_variable_set, class_variables, const_defined?, const_get, const_missing, const_set, constants, define_method, extend_object, extended, freeze, include?, included_modules, included, include, instance_methods, instance_method, method_added, method_defined?, method_removed, method_undefined, module_eval, module_function, name, private_class_method, private_instance_methods, private_method_defined?, private, protected_instance_methods, protected_method_defined?, protected, public_class_method, public_instance_methods, public_method_defined?, public, remove_class_variable, remove_const, remove_method, to_s, undef_method

Module::constants[править]


 Module.constants   => array

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

Module::nesting[править]


 Module.nesting    => array

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"

Module::new[править]


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

  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"

Module#<[править]


 mod < other   =>  true, false, or nil

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

Module#<=[править]


 mod <= other   =>  true, false, or nil

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

Module#<=>[править]


 mod <=> other_mod   => -1, 0, +1, or nil

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 or if mod has no relationship with other_mod. Returns nil if other_mod is not a module.

Module#==[править]


 obj == other        => true or false
 obj.equal?(other)   => true or false
 obj.eql?(other)     => true or false

Equality---At the Object level, == returns true only if obj and other are the same object. Typically, this method is overridden in descendent 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

Module#===[править]


 mod === obj    => 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.

Module#>[править]


 mod > other   =>  true, false, or nil

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

Module#>=[править]


 mod >= other   =>  true, false, or nil

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

Module#alias_method[править]


 alias_method(new_name, old_name)   => self

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

Module#ancestors[править]


 mod.ancestors -> array

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]

Более одного метода удовлетворяет вашему запросу. Вы можете уточнить ваш запрос, выбрав один из следующих методов:

Module#append_features, Module#append_features===Module#attr===


 attr(symbol, writable=false)    => 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. 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

Module#attr_accessor[править]


 attr_accessor(symbol, ...)    => nil

Equivalent to calling ``attrsymbol, true on each symbol in turn.

  module Mod
    attr_accessor(:one, :two)
  end
  Mod.instance_methods.sort   #=> ["one", "one=", "two", "two="]

Module#attr_reader[править]


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

Module#attr_writer[править]


 attr_writer(symbol, ...)    => nil

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

Module#autoload[править]


 mod.autoload(name, filename)   => nil

Registers filename to be loaded (using Kernel::require) the first time that name (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"

Module#autoload?[править]


 mod.autoload?(name)   => String or nil

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"

Module#class_eval[править]


 mod.class_eval(string [, filename [, lineno]])  => obj
 mod.module_eval {|| block }                     => obj

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

Module#class_variable_get[править]


 mod.class_variable_get(symbol)    => obj

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
  def Fred.foo
    class_variable_get(:@@foo)     #=> 99
  end

Module#class_variable_set[править]


 obj.class_variable_set(symbol, obj)    => obj

Sets the class variable names by symbol to object.

  class Fred
    @@foo = 99
    def foo
      @@foo
    end
  end
  def Fred.foo
    class_variable_set(:@@foo, 101)      #=> 101
  end
  Fred.foo
  Fred.new.foo                             #=> 101

Module#class_variables[править]


 mod.class_variables   => array

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

Module#const_defined?[править]


 mod.const_defined?(sym)   => true or false

Returns true if a constant with the given name is defined by mod.

  Math.const_defined? "PI"   #=> true

Module#const_get[править]


 mod.const_get(sym)    => obj

Returns the value of the named constant in mod.

  Math.const_get(:PI)   #=> 3.14159265358979

Более одного метода удовлетворяет вашему запросу. Вы можете уточнить ваш запрос, выбрав один из следующих методов:

Module#const_missing, Module#const_missing===Module#const_set===


 mod.const_set(sym, obj)    => 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

Module#constants[править]


 mod.constants    => 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).

Module#define_method[править]


 define_method(symbol, method)     => new_method
 define_method(symbol) { block }   => proc

Defines an instance method in the receiver. The method parameter can be a Proc or Method 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>

Module#extend_object[править]


 extend_object(obj)    => obj

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

Module#extended[править]


 extended(p1)

Not documented

Module#freeze[править]


 mod.freeze

Prevents further modifications to mod.

Module#include[править]


 include(module, ...)    => self

Invokes Module.append_features on each parameter in turn.

Module#include?[править]


 mod.include?(module)    => true or false

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

Module#included[править]


 included( othermod )

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

Module#included_modules[править]


 mod.included_modules -> array

Returns the list of modules included in mod.

  module Mixin
  end
  module Outer
    include Mixin
  end
  Mixin.included_modules   #=> []
  Outer.included_modules   #=> [Mixin]

Module#instance_method[править]


 mod.instance_method(symbol)   => unbound_method

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!

Module#instance_methods[править]


 mod.instance_methods(include_super=true)   => array

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(false)         #=> ["method2"]
  C.instance_methods(false)         #=> ["method3"]
  C.instance_methods(true).length   #=> 43

Module#method_added[править]


 method_added(p1)

Not documented

Module#method_defined?[править]


 mod.method_defined?(symbol)    => 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). 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

Module#method_removed[править]


 method_removed(p1)

Not documented

Module#method_undefined[править]


 method_undefined(p1)

Not documented

Module#module_eval[править]


 mod.class_eval(string [, filename [, lineno]])  => obj
 mod.module_eval {|| block }                     => obj

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

Module#module_function[править]


 module_function(symbol, ...)    => self

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"

Module#name[править]


 mod.name    => string

Returns the name of the module mod.

Module#private[править]


 private                 => self
 private(symbol, ...)    => self

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

Module#private_class_method[править]


 mod.private_class_method(symbol, ...)   => 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

Module#private_instance_methods[править]


 mod.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"]

Module#private_method_defined?[править]


 mod.private_method_defined?(symbol)    => true or false

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

Module#protected[править]


 protected                => self
 protected(symbol, ...)   => self

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

Module#protected_instance_methods[править]


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

Module#protected_method_defined?[править]


 mod.protected_method_defined?(symbol)   => true or false

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

Module#public[править]


 public                 => self
 public(symbol, ...)    => self

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

Module#public_class_method[править]


 mod.public_class_method(symbol, ...)    => mod

Makes a list of existing class methods public.

Module#public_instance_methods[править]


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

Module#public_method_defined?[править]


 mod.public_method_defined?(symbol)   => true or false

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

Module#remove_class_variable[править]


 remove_class_variable(sym)    => obj

Removes the definition of the sym, returning that constant's value.

  class Dummy
    @@var = 99
    puts @@var
    remove_class_variable(:@@var)
    puts(defined? @@var)
  end

produces:

  99
  nil

Module#remove_const[править]


 remove_const(sym)   => obj

Removes the definition of the given constant, returning that constant's value. Predefined classes and singleton objects (such as true) cannot be removed.

Module#remove_method[править]


 remove_method(symbol)   => self

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

Module#to_s[править]


 mod.to_s   => string

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.

Module#undef_method[править]


 undef_method(symbol)    => self

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)