Chapter 2. Methods and Classes: Getting Organized
You’ve been missing out. You’ve been calling methods and creating objects like a pro. But the only methods you could call, and the only kinds of objects you could create, were the ones that Ruby defined for you. Now, it’s your turn. You’re going to learn to create your own methods. You’ll also create your own classes—templates for new objects. You’ll decide what objects based on your class will be like. You’ll use instance variables to define what those objects know, and instance methods to define what they do. And most importantly, you’ll discover how defining your own classes can make your code easier to read and maintain.
Defining methods
Got-A-Motor, Inc., is working on their “virtual test-drive” app, which lets their customers try vehicles out on their computers without needing to visit a showroom. For this first version, they need methods to let users step on the virtual gas, sound the virtual horn, and turn on the virtual headlights in low-beam or high-beam mode.
Method definitions look like this in Ruby:
If you want calls to your method to include arguments, you’ll need to add parameters to the method definition. Parameters appear after the method name, within parentheses. (You should leave off the parentheses if there are no parameters.) ...
Get Head First Ruby 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.