The Enumerable module of Ruby is very powerful. It defines a lot of method used by container objects (arrays, sets, hashes) like:

- map

- each

- count

If you want to get the full list of the methods in the Enumerable module you can run:

>> Enumerable.instance_methods(false).sort

=> [:all?, :any?, :chunk, :chunk_while, :collect, :collect_concat, :count,:cycle, :detect, :drop, :drop_while, :each_cons, :each_entry, :each_slice, :each_with_index, :each_with_object, :entries, :find, :find_all, :find_index, :first, :flat_map, :grep, :grep_v, :group_by, :include?, :inject, :lazy, :map, :max, :max_by, :member?, :min, :min_by, :minmax, :minmax_by, :none?, :one?, :partition, :reduce, :reject, :reverse_each, :select, :slice_after, :slice_before, :slice_when, :sort, :sort_by, :sum, :take, :take_while, :to_a, :to_h, :uniq, :zip]

There is a well-kept secret though.

You can MAGICALLY add all of the above method to any Ruby object by doing this 2 simple things:

- Adding the Enumerable mixin

- Defining the each method

class CarFactory

include Enumerable



yield car

end

end

end def each @container .each do |car|yield carendendend

After that, you will be able to use ALL of the method:

car_factory = CarFactory.new

car_factory.count

car_factory.include?

car_factory.flat_map

#etc...

Here is the complete example:



attr_accessor :color, :brand

def initialize(color, brand)





end

end class Carattr_accessor :color, :branddef initialize(color, brand) @color = color @brand = brandendend class CarFactory

include Enumerable





end def initialize(brand) @container = [] @brand = brandend

raise ArgumentError, "Argument must be an instance of Car" unless item.instance_of? Car



end def <@container << itemend



yield car

end

end

end def each @container .each do |car|yield carendendend car_factory = CarFactory.new("Ford")

car_factory << Car.new("red", "Ford")

car_factory << Car.new("blue", "Ford")

car_factory << Car.new("white", "Ford") car_factory.each do |car|

puts car.color, car.brand

end

So, here is a challenge for you: Create a class and make it enumerable

(by the way, you are not allowed to copy paste the example above!! haha! try to find another use case, that will be more helpful for your learning :)