More Well Grounded Rubyist

When you call one method from another in the same object, you do not need to write

self.method_name

You can just write

method_name

The exception is if the method name ends with an equal sign. Calling

self.method

calls the instance’s method. Using the form

def self.method
end

 

defines a class method. To call those, you must use

self.class.some_method

to call it from another method.

Global variables start with a dollar sign like this:

$abundance

Class variables start with two at signs:

@@counter

The class variable is actually for the class hierarchy, not just the class. So if you have a variable

@@area

in the Shape class and Circle inherits from it, then they will share that variable. For a subclass to have its own class variable, reference it with the word “self”:

self.class.total_count

The book also talked about public, private and protected methods. You can just list the methods you want to be private with the “private” keyword:

private :do_something :stop_talking :stay_secret

And you can call them as regular methods in the object.

The book also had a section on protected methods, but honestly I did not read it too carefully. Protected methods started in C++. I have read that the designer of C++, Bjarne Stroustrup, regards them as a mistake, and that if he could start C++ over again he would not put in protected methods. Good enough for me.

 

There are 245 words in this article.