Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is `each` in ruby not defined in the enumerable module?

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?

like image 916
mrageh Avatar asked Mar 18 '23 13:03

mrageh


1 Answers

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]
like image 177
Ajedi32 Avatar answered Apr 01 '23 21:04

Ajedi32