Chapter 3. Organizing objects with classes

 

This chapter covers

  • Creating multiple objects with classes
  • Setting and reading object state
  • Automating creation of attribute read and write methods
  • Class inheritance mechanics
  • Syntax and semantics of Ruby constants

Creating a new object with Object.new—and equipping that object with its own methods, one method at a time—is a great way to get a feel for the object-centeredness of Ruby programming. But this approach doesn’t exactly scale; if you’re running an online box office and your database has to process records for tickets by the hundreds, you’ve got to find another way to create and manipulate ticket-like objects in your Ruby programs.

Sure enough, Ruby gives you a full suite of programming techniques for creating objects on a batch basis. You don’t have to define a separate price method for every ticket. Instead, you can define a ticket class, engineered in such a way that every individual ticket object automatically has the price method. You’ll see examples in this chapter.

Defining a class lets you group behaviors (methods) into convenient bundles, so that you can quickly create many objects that behave essentially the same way. You can also add methods to individual objects, if that’s appropriate for what you’re trying to do in your program. But you don’t have to do that with every object if you model your domain into classes.

3.1. Classes and instances

3.2. Instance variables and object state

3.3. Setter methods

3.4. Attributes and the attr_* method family

3.5. Inheritance and the Ruby class hierarchy

3.6. Classes as objects and message receivers

3.7. Constants up close

3.8. Nature vs. nurture in Ruby objects

Summary

sitemap