
Saved by Harold T. Harper
The Well-Grounded Rubyist
Saved by Harold T. Harper
So far, we’ve arranged things in such a way that we set the values of the instance variables at the point where the object is created and can then retrieve those values at any point during the life of the object. That arrangement is often adequate, but it’s not symmetrical. What if you want to set the values of instance variables at some point othe
... See moreGlobals appear to solve lots of design problems: you don’t have to worry about scope, and multiple classes can share information by stashing it in globals rather than designing objects that have to be queried with method calls.
Some objects in Ruby are stored in variables as immediate values. These include integers, symbols (which look like :this), and the special objects true, false, and nil. When you assign one of these values to a variable (x = 1), the variable holds the value itself, rather than a reference to it.
And there’s an attr_writer method, too: class Ticket attr_writer :price end With that single line, we wrote (or, rather, Ruby wrote for us) our price= setter method. One line takes the place of three. In the case of the reader methods, one line took the place of nine!
You also have to use return if you want to return from somewhere in the middle of a method. But whether you use return or not, something will be returned from every method call. Even a call to an empty method body, consisting of just the def and end statements, returns nil.
Similarly, even a call to the puts method has a return value—namely, nil. If you type a puts statement in irb, irb will obediently execute it, and it will also print out the return value of puts: $ irb --simple-prompt >> puts "Hello" Hello => nil
You’re the object, and someone sends you a message. You have to figure out how to respond to it—or whether you even can respond to it. Here’s a bit of object stream-of-consciousness: I’m a Ruby object, and I’ve been sent the message 'report'. I have to try to find a method called report in my method-lookup path. report, if it exists, resides in a c
... See moreEvery object in Ruby has a unique ID number associated with it. You can see an object’s ID by asking the object to show you its object_id,
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 more