From a13aee62d243105ffd3b5178a4d4d6b99c2b2755 Mon Sep 17 00:00:00 2001 From: drbrain Date: Sat, 5 Jan 2013 01:23:49 +0000 Subject: * doc/syntax/modules_and_classes.rdoc: Added documentation of syntax for Modules and Classes. * doc/syntax/methods.rdoc: Moved some text to the Modules and Classes syntax document. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@38701 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- doc/syntax/methods.rdoc | 32 ++------------------------------ 1 file changed, 2 insertions(+), 30 deletions(-) (limited to 'doc/syntax/methods.rdoc') diff --git a/doc/syntax/methods.rdoc b/doc/syntax/methods.rdoc index b3233e647a..832ba269b0 100644 --- a/doc/syntax/methods.rdoc +++ b/doc/syntax/methods.rdoc @@ -38,7 +38,7 @@ The standard syntax to define a method: # ... end -add the method to a class. You can define an instance method on a specific +adds the method to a class. You can define an instance method on a specific class with the +class+ keyword: class C @@ -47,24 +47,6 @@ class with the +class+ keyword: end end -In many languages, the +class+ keyword lets the compiler know that you're -creating a class. This is true in Ruby, too, the first time you use the -_class_ keyword: when it sees that you're _opening_ a class for -the first time, it creates it. When you open a class that already exists, Ruby -enables to you _extend_ it with new methods. You can even extend core -classes: - - class String - def hello - "Hello, world!" - end - end - - "".hello # returns "Hello, world!" - -However, This is somewhat risky due to namespace pollution so this ability is -best used sparingly. - A method may be defined on another object. You may define a "class method" (a method that is defined on the class, not an instance of the class) like this: @@ -74,16 +56,6 @@ method that is defined on the class, not an instance of the class) like this: end end -or a more concrete example: - - class String - def self.hello - "Hello, world!" - end - end - - String.hello # returns "Hello, world!" - However, this is simply a special case of a greater syntactical power in Ruby, the ability to add methods to any object. Classes are objects, so adding class methods is simply adding methods to the Class object. @@ -98,7 +70,7 @@ The syntax for adding a method to an object is as follows: greeting.broaden # returns "Hello, world!" -_self_ is a keyword referring to the current object under consideration ++self+ is a keyword referring to the current object under consideration by the compiler, which might make the use of +self+ in defining a class method above a little clearer. Indeed, the example of adding a +hello+ method to the class +String+ can be rewritten thus: -- cgit v1.2.3