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 }
source share