Methods

 
   

Ruby Way
By Hal Fulton
Slots : 1.0
Table of Contents
 


Methods are not objects in Ruby. This is despite the fact that things such as classes, numbers, bindings, and threads are objects.

Ruby methods are not functions. Any time you see def in Ruby code, you are seeing a method definition. It has no namespace or attributes of its own. It cannot typically be nested. And again, it is not an object.

It follows that method names are not variable names. Method names should begin with a lowercase letter or underscore; they may have ! or ? suffixes. They do not use a prefix to denote scope, but you can make them private, protected, or public. (We should note that it is possible to capitalize a method name, but it is unconventional and could lead to minor difficulties.)

Many operators are implemented as methods, and can be directly overridden without the use of magic attributes such as __add__, __gt__, __setattr__, or __getitem__.

 

 def +(arg)   # ...  end def >(arg)   # ...  end # etc. 

Combinations such as += are syntax sugar, not operators, so redefining + will affect += also.

There are specially hooked methods in Ruby: each, coerce, <=>, to_str, and to_ary, among others. See the Enumerable and Comparable modules.


   

 

 



The Ruby Way
The Ruby Way, Second Edition: Solutions and Techniques in Ruby Programming (2nd Edition)
ISBN: 0672328844
EAN: 2147483647
Year: 2000
Pages: 119
Authors: Hal Fulton

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net