At the object level, data storage (state) is handled by instance variables (a name that's derived from the instantiation process mentioned). Think of instance variables as storage containers that are attached to the object, but to which other objects do not have direct access.
To store or retrieve data from these variables, another object must call an accessor method defined on the object. An accessor method has the ability to set (and get) the value of the object's instance variables.
Let's look at how instance variables and accessor methods relate to each other, and how they're implemented in Ruby.
Instance variables are bound to an object, and contain values for that object only. Revisiting our car example, the mileage values for a number of different Car objects are likely to differ, as each car will have a different mileage. Therefore, mileage is held in an instance variable.
An instance variable can be recognized by its prefix: a single “at” (@) sign. What's more, instance variables don't even need to be declared! There's only one issue: we don't have any way to retrieve or change them from outside the object once they do exist. This is where instance methods come into play.
A Link to Social Media
I like to think of instance variables as the inspiration for mentions on Twitter and social media. I have no idea if this is true, but Twitter did start life in Ruby.
Data storage and retrieval is not the only capability that can be bound to a specific object; functionality can also be bound to objects. We achieve this binding through the use of instance methods that are specific to an object. Invoking an instance method (in other words, sending a message that contains the method name to an object) will invoke that functionality on the receiving object only.
Instance methods are defined using the def keyword, and end with the end keyword.
Enter the following example into a new Ruby shell:
$ irb irb> class Car
irb> def open_trunk
irb> # code to open trunk goes here
irb> end => nil
irb> kitt = Car.new
What you've done is define a class called Car, which has an instance method with the name open_trunk. A Car object instantiated from this class will—possibly using some fancy robotics connected to our Ruby program—open its trunk when its open_trunk method is called. Ignore that nil return value for the moment; we'll look at nil values in the next section.
If you want to change selection, open original toplevel document below and click on "Move attachment"
|last reprioritisation on
|suggested re-reading day
|started reading on
|finished reading on