Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

Chapter 7. Reaching into a Collection wi... > The Inimitable Enumerable

The Inimitable Enumerable

If you do find yourself creating an aggregate class and equipping it with an internal iterator, you should probably consider including the Enumerable mixin module in your class. Enumerable is like one of those late-night gadget commercials: To mix in Enumerable, you need only make sure that your internal iterator method is named each and that the individual elements that you are going to iterate over have a reasonable implementation of the <=> comparison operator. For this one low, low price, Enumerable will add to your class a whole range of useful methods. Among the handy things you get from Enumerable are include?(obj), which returns true if the object supplied as a parameter is part of your aggregate object, plus min and max, which return exactly what you would expect.

The Enumerable mixin also includes more exotic methods such as all?, which takes a block and returns true if the block returns true for all of the elements. The Array class includes Enumerable, so we can write one line of code to return true if all the strings in an array are less than four characters long:


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint