
Saved by Harold T. Harper
The Well-Grounded Rubyist
Saved by Harold T. Harper
Let’s solve the problem, initially, with a set_price method that allows us to set, or reset, the price of an existing ticket.
The main difference between inheriting from a class and mixing in a module is that you can mix in more than one module. No class can inherit from more than one class. In cases where you want numerous extra behaviors for a class’s instances—and you don’t want to stash them all in the class’s superclass and its ancestral classes—you can use modules t
... See moreAt the other end of the process, every method call hands back—returns—a value.
As per the nesting, the first puts 1 gives you 1; the second 2 gives you 2.
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 morePublic is the default access level; if you don’t specify that a method is protected or private, it’s public. Public instance methods are the common currency of Ruby programming. Most of the messages you send to objects are calling public methods.
Conditional execution often involves more than one branch; you may want to do one thing if the condition succeeds and another if it doesn’t. For example, if the password is correct, let the user in; otherwise, print an error message. Ruby makes full provisions for multiple conditional branches, using else and elsif.
puts adds a newline to the string it outputs if there isn’t one at the end already; print doesn’t. print prints exactly what it’s told to and leaves the cursor at the end.
Sometimes you want an if condition to be negative: if something isn’t true, then execute a given segment of code. You can do this in several ways. Negating conditions with not and ! One way to negate a condition is to use the not keyword: if not (x == 1) You can also use the negating ! (exclamation point, or bang) operator: if !(x == 1)