1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Understanding Mixins is Important


The above example is inconsequential. It's a solution to a hypothetical problem. But mixins are used in real code, and you've been using them all along. Take a look at the methods in the Enumerable mixin module. You've seen these before, right? They're things like collect, find, map and inject, things you probably use regularly with Arrays or Hashes. But they're not Array or Hash methods, they belong to the Enumberable mixin.

Looking back to the previous drawable elements example, you'll see that all the drawable elements had to have a base set of methods the mixin can build on. Here, with the Enumerable mixin, there are two methods that are important. The collection only needs to implement the each method, with iterates over the collection. Given that, all the methods like find and map simply use each to do its job. Second, the objects that are yielded by each should implement the <=> operator. This will allow the Enumerable to be able to sort the collection, and implement methods like min or max.

  1. About.com
  2. Technology
  3. Ruby
  4. Beginning Ruby
  5. Understanding Mixins is Important

©2014 About.com. All rights reserved.