Movatterモバイル変換


[0]ホーム

URL:


HomeClassesMethods

Files

Class Index[+]

Quicksearch
No matching classes.

Modules

Modules serve two purposes in Ruby, namespacing and mix-in functionality.

A namespace can be used to organize code by package or functionality thatseparates common names from interference by other packages. For example,the IRB namespace provides functionality for irb that prevents a collisionfor the common name “Context”.

Mix-in functionality allows sharing common methods across multiple classesor modules. Ruby comes with theEnumerable mix-in module which providesmany enumeration methods based on theeach method andComparable allows comparison of objectsbased on the<=> comparison method.

Note that there are many similarities between modules and classes. Besidesthe ability to mix-in a module, the description of modules below alsoapplies to classes.

Module Definition

A module is created using themodule keyword:

moduleMyModule# ...end

A module may be reopened any number of times to add, change or removefunctionality:

moduleMyModuledefmy_methodendendmoduleMyModulealiasmy_aliasmy_methodendmoduleMyModuleremove_method :my_methodend

Reopening classes is a very powerful feature of Ruby, but it is best toonly reopen classes you own. Reopening classes you do not own may lead tonaming conflicts or difficult to diagnose bugs.

Nesting

Modules may be nested:

moduleOutermoduleInnerendend

Many packages create a single outermost module (or class) to provide anamespace for their functionality.

You may also define inner modules using:: provided the outermodules (or classes) are already defined:

moduleOuter::Inner::GrandChildend

Note that this will raise aNameError ifOuterandOuter::Inner are not already defined.

This style has the benefit of allowing the author to reduce the amount ofindentation. Instead of 3 levels of indentation only one is necessary.However, the scope of constant lookup is different for creating a namespaceusing this syntax instead of the more verbose syntax.

Scope

self

self refers to the object that defines the current scope.self will change when entering a different method or whendefining a new module.

Constants

Accessible constants are different depending on the module nesting (whichsyntax was used to define the module). In the following example theconstantA::Z is accessible from B as A is part of thenesting:

moduleAZ =1moduleBpModule.nesting#=> [A::B, A]pZ#=> 1endend

However, if you use:: to defineA::B withoutnesting it insideA, aNameError exception will be raised becausethe nesting does not includeA:

moduleAZ =1endmoduleA::BpModule.nesting#=> [A::B]pZ#=> raises NameErrorend

If a constant is defined at the top-level you may preceded it with:: to reference it:

Z =0moduleAZ =1moduleBp::Z#=> 0endend

Methods

For method definition documentation see the syntax documentation formethods.

Class methods may be called directly. (Thisis slightly confusing, but a method on a module is often called a “classmethod” instead of a “module method”. See alsoModule#module_functionwhich can convert an instance method into a class method.)

When a class method references a constant, it uses the same rules asreferencing it outside the method as the scope is the same.

Instance methods defined in a module are only callable when included. These methods have access to the constants defined when they were includedthrough the ancestors list:

moduleAZ =1defzZendendincludeApself.class.ancestors#=> [Object, A, Kernel, BasicObject]pz#=> 1

Visibility

Ruby has three types of visibility. The default ispublic. Apublic method may be called from any other object.

The second visibility isprotected. When calling a protectedmethod the sender must be a subclass of the receiver or the receiver mustbe a subclass of the sender. Otherwise aNoMethodError will be raised.

Protected visibility is most frequently used to define== andother comparison methods where the author does not wish to expose anobject's state to any caller and would like to restrict it only toinherited classes.

Here is an example:

classAdefn(other)other.mendendclassB<Adefm1endprotected :mendclassC<Benda =A.newb =B.newc =C.newc.nb#=> 1 -- C is a subclass of Bb.nb#=> 1 -- m called on defining classa.nb# raises NoMethodError A is not a subclass of B

The third visibility isprivate. A private method may only becalled from inside the owner class without a receiver, or with a literalself as a receiver. If a private method is called with areceiver other than a literalself, aNoMethodError will be raised.

classAdefwithoutmenddefwith_selfself.menddefwith_otherA.new.menddefwith_renamedcopy =selfcopy.menddefm1endprivate :menda =A.newa.without#=> 1a.with_self#=> 1a.with_other# NoMethodError (private method `m' called for #<A:0x0000559c287f27d0>)a.with_renamed# NoMethodError (private method `m' called for #<A:0x0000559c285f8330>)

alias andundef

You may also alias or undefine methods, but these operations are notrestricted to modules or classes. See the miscellaneous syntax section fordocumentation.

Classes

Every class is also a module, but unlike modules a class may not bemixed-in to another module (or class). Like a module, a class can be usedas a namespace. A class also inherits methods and constants from itssuperclass.

Defining a class

Use theclass keyword to create a class:

classMyClass# ...end

If you do not supply a superclass your new class will inherit fromObject. You may inherit from a differentclass using< followed by a class name:

classMySubclass<MyClass# ...end

There is a special classBasicObjectwhich is designed as a blank class and includes a minimum of built-inmethods. You can useBasicObject tocreate an independent inheritance structure. See theBasicObject documentation for furtherdetails.

Inheritance

Any method defined on a class is callable from its subclass:

classAZ =1defzZendendclassB<AendpB.new.z#=> 1

The same is true for constants:

classAZ =1endclassB<AdefzZendendpB.new.z#=> 1

You can override the functionality of a superclass method by redefining themethod:

classAdefm1endendclassB<Adefm2endendpB.new.m#=> 2

If you wish to invoke the superclass functionality from a method usesuper:

classAdefm1endendclassB<Adefm2+superendendpB.new.m#=> 3

When used without any argumentssuper uses the arguments givento the subclass method. To send no arguments to the superclass method usesuper(). To send specific arguments to the superclass methodprovide them manually likesuper(2).

super may be called as many times as you like in the subclassmethod.

Singleton Classes

The singleton class (also known as the metaclass or eigenclass) of anobject is a class that holds methods for only that instance. You canaccess the singleton class of an object usingclass <<object like this:

classCendclass<<C# self is the singleton class hereend

Most frequently you'll see the singleton class accessed like this:

classCclass<<self# ...endend

This allows definition of methods and attributes on a class (or module)without needing to writedef self.my_method.

Since you can open the singleton class of any object this means that thiscode block:

o =Object.newdefo.my_method1+1end

is equivalent to this code block:

o =Object.newclass<<odefmy_method1+1endend

Both objects will have amy_method that returns2.

Generated with Rubydoc Rdoc Generator 0.42.0.


[8]ページ先頭

©2009-2025 Movatter.jp