Objects and Attributes

The BookInStock objects we’ve created so far have an internal state (the ISBN and price). That state is private to those objects—no other object can access an object’s instance variables. In general, this is a Good Thing. It means that the object is solely responsible for maintaining its own consistency. (We feel obligated to note here that there’s no such thing as perfect privacy in Ruby, and you shouldn’t depend on Ruby’s language privacy for security purposes.)

A totally secretive object is pretty useless—you can create it, but then you can’t do anything with it. You’ll normally define methods that let you access and manipulate the state of an object, allowing the outside world to interact with the object. These externally ...

Get Programming Ruby 3.3 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.