In Ruby, the Enumerable module mixes with collection classes and relies on a class serving each method, which gives each item in the collection.
Ok, so if I want to use Enumerable in my class, I just implement each [1]:
class Colors include Enumerable def each yield "red" yield "green" yield "blue" end end > c = Colors.new > c.map { |i| i.reverse } #=> ["der", "neerg", "eulb"]
This works as expected.
But if I override each method in an existing class with Enumerable, it does not break functions like map . Why not?
class Array def each puts "Nothing here" end end > [1,2,3].each {|num| puts num } #=> "Nothing here" > [1,2,3].map {|num| num**2 } #=> [1,4,9]
[1]: from http://www.sitepoint.com/guide-ruby-collections-iii-enumerable-enumerator/
source share