
Saved by Harold T. Harper
The Well-Grounded Rubyist
Saved by Harold T. Harper
Every time you include a module in a class, you’re affecting what happens when instances of that class have to resolve messages into method names. The same is true of prepend. The difference is that if you prepend a module to a class, the object looks in that module first, before it looks in the class.
Conveniently, Ruby objects come with their own storage and retrieval mechanisms for values: instance variables.
Information and data associated with a particular object embodies the state of the object. We need to be able to do the following: Set, or reset, the state of an object (say to a ticket, “You cost $11.99.”). Read back the state (ask a ticket, “How much do you cost?”).
Ticket.most_expensive is a different case, in that it doesn’t create a new object—but it’s still a method that belongs logically to the class. Finding the most expensive ticket in a list of tickets can be viewed as an operation from above, something that’s done collectively with respect to tickets, rather than something that’s done by an individual
... See moreConditional statements always end with the word end.
Sample method signatures with required, optional, and default-valued arguments
This example also illustrates the fact that all the code in class- and module-definition blocks gets executed when it’s first encountered, whereas methods aren’t executed until an object is sent the appropriate message. That’s why the value of a that’s set inside the show_a method is displayed last among the five values that the program prints; the
... See moreAfter starting irb, you type Ruby code into it, and it executes the code and prints out the resulting value.
So 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.