Chapter 10. Comparable and Enumerable: Ready-Made Mixes
You’ve seen that mixins can be useful. But you haven’t seen their full power yet. The Ruby core library includes two mixins that will blow your mind. The first, Comparable
, is used for comparing objects. You’ve used operators like <
, >
, and ==
on numbers and strings, but Comparable
will let you use them on your classes.
The second mixin, Enumerable
, is used for working with collections. Remember those super-useful find_all
, reject
, and map
methods that you used on arrays before? Those came from Enumerable
. But that’s a tiny fraction of what Enumerable
can do. And again, you can mix it into your classes. Read on to see how!
Mixins built into Ruby
Now that you know how modules work, let’s take a look at some useful modules that are included with the Ruby language...
Remember comparing numbers using <
, >
, and ==
in the guessing game in Chapter 1? You may recall that comparison operators are actually methods in Ruby.
All the numeric classes need comparison operators, so the creators of Ruby could have just added them to the Numeric
class, which is a superclass of Fixnum
, Float
, and all the other numeric classes in Ruby.
But the String
class needs comparison operators, too. And it doesn’t seem wise to make String
a subclass of Numeric
. For one thing, String
would inherit a bunch of methods like abs
(which gives the absolute value of a number) ...
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.