Understanding comparable mixin and enumerated mixin

I am new and studying ruby. I would like to better understand the question asked. I don't understand the use of a comparable mixin and enumerated mixin. I mean, we don’t include them 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 their explicit use?

+4
source share
2 answers

Great question Akash!

Sometimes it’s not β€œjust” how you can compare two objects! What if you have a Dog class? How do you compare two instances of Dog? What should be the comparison based on? Is it enough to compare their name? their breeds? their DNA? This is really for you. And then, when you can incorporate Comparable into your model and implement the minimum function needed to determine what makes two instances of Dog the same. You define a comparison. After you have defined the comparator <=> in your module, your object can then be compared for equality or sorted or ordered, because the ruby ​​will know HOW to compare one instance with another.

Similarly, including the Enumerable module, your class can iterate over the set of its instances. After you implement each method in your class, you get all the methods of the Enumerable module available in your class. In your class, methods like map / collect, etc. can be used.

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 } 
+6
source

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

Without Comparable mixin, you would like to define > , < , >= , <= and == in your class, whereas if you enable Comparable , you only need to define <=> . Comparable contains implementations of these other methods based on your <=> method.

Similarly to the enumerated, you only need to define each , and in return you will get map , inject , partition , reject , etc.

+5
source

All Articles