
Saved by Harold T. Harper
The Well-Grounded Rubyist
Saved by Harold T. Harper
The top level (outside of all definition blocks) has its own local scope. Every class or module-definition block (class, module) has its own local scope, even nested class-/module-definition blocks. Every method definition (def) has its own local scope; more precisely, every call to a method generates a new local scope, with all local variables res
... See moreSo you can reassign to a constant, but doing so isn’t considered good practice. If you want a reusable identifier, you should use a variable.
We can continue the cascade downward: class Ezine < Magazine end Instances of Ezine have both publisher and editor attributes, as defined in the superclass and super-superclass of Ezine. Note that it’s not mandatory to add new methods to every subclass.
This opens up our prospects immensely. We can create, manipulate, compare, and examine any number of tickets at the same time, without having to write separate methods for each of them. All the tickets share the resources of the Ticket class. At the same time, each ticket has its own set of instance variables to store state information.
A typical class consists of a collection of method definitions. Classes usually exist for the purpose of being instantiated—that is, of having objects created that are instances of the class.
The symbol < designates Magazine as a subclass of Publication.
Unlike a local variable, the instance variable @name retains the value assigned to it even after the method in which it was initialized has terminated. This property of instance variables—their survival across method calls—makes them suitable for maintaining state in an object.
The method most_expensive is defined directly on the class object Ticket, in singleton-method style. A singleton method defined on a class object is commonly referred to as a class method of the class on which it’s defined. The idea of a class method is that you send a message to the object that’s the class rather than to one of the class’s instanc
... See moreAny time you see repetition on that scale, you should try to trim it—not by reducing what your program does, but by finding a way to express the same thing more concisely. In pursuit of this conciseness, Ruby is one step ahead: it provides a built-in shortcut that automatically creates a method that reads and returns the value of the instance varia
... See more