
Saved by Harold T. Harper
The Well-Grounded Rubyist
Saved by Harold T. Harper
Modules open up lots of possibilities—particularly for sharing code among more than one class, because any number of classes can mix in the same module.
At its simplest, the idea behind a class variable is that it provides a storage mechanism that’s shared between a class and instances of that class, and that’s not visible to any other objects. No other entity can fill this role. Local variables don’t survive the scope change between class definitions and their inner method definitions.
Every expression in Ruby evaluates to an object, and every object in Ruby has a truth value. The truth value of almost every object in Ruby is true. The only objects whose truth value (or Boolean value) is false are the object false and the special nonentity object nil.
When you need to set or
A constant defined in a class can be referred to from inside the class’s instance or class methods. Let’s say you wanted to make sure that every ticket was for a legitimate venue. You could rewrite the initialize method like this: def initialize(venue, date) if VENUES.include?(venue) 1 @venue = venue else raise ArgumentError, "Unknown venue #{
... See moreSo class method has a fuzzy meaning and a sharp meaning. Fuzzily, any method that gets called directly on a Class object is a class method. Sharply, a class method is defined, not just called, directly on a Class object. You’ll hear it used both ways, and as long as you’re aware of the underlying engineering and can make the sharp distinctions when
... See moreConstant lookup—the process of resolving a constant identifier, or finding the right match for it—bears a close resemblance to searching a file system for a file in a particular directory. For one thing, constants are identified relative to the point of execution. Another variant of our example illustrates this: module M class C class D module N X
... See moreWhen you want something done —a calculation, an output operation, a data comparison—you ask an object to do it. Rather than ask in the abstract whether a equals b, you ask a whether it considers itself equal to b. If you want to know whether a given student is taking a class from a given teacher, you ask the student, “Are you a student of this teach
... See moreThe issue at hand is that it’s useful to have a way to maintain state in a class. You saw this even in the simple Car class example. We wanted somewhere to stash class-relevant information, like the makes of cars and the total number of cars manufactured.
For every object in Ruby, there can and must be one or more references to that object. If there are no references, the object is considered defunct, and its memory space is released and reused.