Ruby defines most iterator methods in enumerable and includes that in Array, Hash etc.
However each
is defined within every class and not included in enumerable.
Am guessing this was a deliberate choice but am wondering why?
Is there a technical limitation as to why each
is not included in Enumerable?
From the documentation for Enumerable
:
The Enumerable mixin provides collection classes with several traversal and searching methods, and with the ability to sort. The class must provide a method each, which yields successive members of the collection.
So the Enumerable module requires that classes which include it implement each
on their own. All the other methods in Enumerable depend on each
being implemented by the class which includes Enumerable.
For example:
class OneTwoThree
include Enumerable
# OneTwoThree has no `each` method!
end
# This throws an error:
OneTwoThree.new.map{|x| x * 2 }
# NoMethodError: undefined method `each' for #<OneTwoThree:0x83237d4>
class OneTwoThree
# But if we define an `each` method...
def each
yield 1
yield 2
yield 3
end
end
# Then it works!
OneTwoThree.new.map{|x| x * 2 }
#=> [2, 4, 6]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With