From ac67a2b6d45d2ab443517110674d240bd1ee8ed6 Mon Sep 17 00:00:00 2001 From: drbrain Date: Sat, 5 Jan 2013 20:35:30 +0000 Subject: * 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 --- doc/syntax/modules_and_classes.rdoc | 45 +++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) (limited to 'doc/syntax') diff --git a/doc/syntax/modules_and_classes.rdoc b/doc/syntax/modules_and_classes.rdoc index cca9dc2563..65bd31bf7d 100644 --- a/doc/syntax/modules_and_classes.rdoc +++ b/doc/syntax/modules_and_classes.rdoc @@ -291,3 +291,48 @@ provide them manually like super(2). +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 class << object 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 def self.my_method. + +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+. + -- cgit v1.2.3