understanding comparable mixin and enumerable mixin

依然范特西╮ 提交于 2019-12-05 08:18:43

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 }

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...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!