Chapter 5. Arrays and Blocks: Better Than Loops

image with no caption

A whole lot of programming deals with lists of things. Lists of addresses. Lists of phone numbers. Lists of products. Matz, the creator of Ruby, knew this. So he worked really hard to make sure that working with lists in Ruby is really easy. First, he ensured that arrays, which keep track of lists in Ruby, have lots of powerful methods to do almost anything you might need with a list. Second, he realized that writing code to loop over a list to do something with each item, although tedious, is something developers were doing a lot. So he added blocks to the language, and removed the need for all that looping code. What is a block, exactly? Read on to find out...

Arrays

Your new client is working on an invoicing program for an online store. They need three different methods, each of which works with the prices on an order. The first method needs to add all the prices together to calculate a total. The second will process a refund to the customer’s account. And the third will take 1/3 off each price and display the discount.

image with no caption

Hmm, so you have a list of prices (a collection of them, if you will), and you don’t know in advance how many there will be... That means you can’t use variables to store them—there’s no way to know how many variables to ...

Get Head First Ruby now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.