mirror of
https://github.com/ruby/ruby.git
synced 2022-11-09 12:17:21 -05:00
* doc/syntax/modules_and_classes.rdoc: Added singleton classes
documentation. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@38710 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
This commit is contained in:
parent
902a36c1f6
commit
ac67a2b6d4
2 changed files with 50 additions and 0 deletions
|
@ -1,3 +1,8 @@
|
|||
Sun Jan 6 05:35:18 2013 Eric Hodel <drbrain@segment7.net>
|
||||
|
||||
* doc/syntax/modules_and_classes.rdoc: Added singleton classes
|
||||
documentation.
|
||||
|
||||
Sun Jan 6 02:22:00 2013 Zachary Scott <zachary@zacharyscott.net>
|
||||
|
||||
* lib/webrick/httpservlet/abstract.rb (WEBrick::HTTPServlet): Typo in
|
||||
|
|
|
@ -291,3 +291,48 @@ provide them manually like <code>super(2)</code>.
|
|||
|
||||
+super+ may be called as many times as you like in the subclass method.
|
||||
|
||||
= Singleton Classes
|
||||
|
||||
The singleton class (also known as the metaclass or eigenclass) of an object is
|
||||
a class that holds methods for only that instance. You can access the
|
||||
singleton class of an object using <code>class << object</code> like this:
|
||||
|
||||
class C
|
||||
end
|
||||
|
||||
class << C
|
||||
# self is the singleton class here
|
||||
end
|
||||
|
||||
Most frequently you'll see the singleton class accessed like this:
|
||||
|
||||
class C
|
||||
class << self
|
||||
# ...
|
||||
end
|
||||
end
|
||||
|
||||
This allows definition of methods and attributes on a class (or module) without
|
||||
needing to write <code>def self.my_method</code>.
|
||||
|
||||
Since you can open the singleton class of any object this means that this code
|
||||
block:
|
||||
|
||||
o = Object.new
|
||||
|
||||
def o.my_method
|
||||
1 + 1
|
||||
end
|
||||
|
||||
is equivalent to this code block:
|
||||
|
||||
o = Object.new
|
||||
|
||||
class << o
|
||||
def my_method
|
||||
1 + 1
|
||||
end
|
||||
end
|
||||
|
||||
Both objects with have a +my_method+ that returns +2+.
|
||||
|
||||
|
|
Loading…
Reference in a new issue