O'Reilly logo

Sams Teach Yourself Ruby in 21 Days by Mark Slagell

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Flow Control

We have seen a few nifty uses for iterators. But there are some limitations on what we can do so far. For example, suppose we had an array and wanted to “select” alternating elements, like this:

[60,62,65,70,72,73,75]   #->  [62,70,73]

The select iterator won't help here, because it looks at the items themselves and not their positions. It is possible to select the elements that actually are odd numbers (that's one of the exercises at the end of the chapter), but not all the elements in odd positions. In a later chapter we'll learn to write custom iterators; perhaps something like select_by_index or select_with_index would be the right thing here.

 # How we would use a select_by_index iterator (if one existed) # to select odd-position ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required