6

I am a newbie and learning ruby. Would like to have a better understanding of the question asked. I don't understand the use of comparable mixin and enumerable mixin. I mean we don't include these in our class when we need to use them, right? if we want to compare two objects we simply write x > y. Then what is the use of explicitly using them?

Akash Soti
  • 583
  • 2
  • 7
  • 13

2 Answers2

8

Great Question Akash!

Sometimes it's not "simple" how two objects can be compared! What if you have a Dog class? How do you compare two Dog instances? What should be the comparison based on? Is it enough to compare their name? their breed? their DNA? It's really upto you. And thats when you can include Comparable in your model and implement the minimum function necessary yourself to define what makes the two Dog instances the same. You define the comparision. Once you have defined the <=> comparator in your module, your object can then be compared for equality or be sorted or ordered because ruby will know HOW to compare one instance against another.

Similarly, including the Enumerable module allows your class the ability to iterate over a collection of its instances. Once you implement the each method in your class, you get the whole Enumerable module's methods available in your class. Methods such as map/collect etc can be used on your class.

class Dog
  include Enumerable

  attr_accessor :puppies, :name

  def initialize(name)
    @name = name
    @puppies = []
  end

  def each(&block)
    @puppies.each do |puppy|
      puts "yielding #{puppy}"
      yield(puppy)
      puts "just yielded #{puppy}"
    end
  end

end


tommy = Dog.new("tommy")
tommy.puppies = ["julie","moti","husky"]

tommy.each do |p|
  puts p
end

big_puppies = tommy.map{|x| x.titleize }
Aditya Sanghi
  • 13,370
  • 2
  • 44
  • 50
6

The point of both of these mixins is that they give you a whole bunch of methods while only having to implement one method yourself.

Without the Comparable mixin you'd want to define >,<, >=, <= and == on your class, whereas if you include Comparable you only need to define <=>. Comparable contains implementations of those other methods, based on your <=> method.

Similarly with enumerable you only need to define each and in return you get map, inject, partition, reject etc...

Frederick Cheung
  • 83,189
  • 8
  • 152
  • 174