comprensión de mixin comparables y mixin enumerables

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?

preguntado el 31 de julio de 12 a las 12:07

2 Respuestas

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 = []

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


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

tommy.each do |p|
  puts p

big_puppies ={|x| x.titleize }

Respondido 31 Jul 12, 13:07

Now I understand much more. Thank you so much for your valuable time. The explanation helped me a lot. - akash soti

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.

Sin el Comparable mixin you'd want to define >,<, >=, <= y == on your class, whereas if you include Comparable solo necesitas definir <=>. Comparable contains implementations of those other methods, based on your <=> método.

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

Respondido 31 Jul 12, 13:07

or like Fred puts it succinctly - aditya sanghi

Thank you Fred, very nicely explained. I believe I understand much more now and have a clear understanding of the topic. I hope I will be able to implement it sensibly in my projects. - akash soti

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.