Why is "everyone" in ruby โ€‹โ€‹not defined in an enumerable module?

Ruby defines most of the iterator methods in an enum and includes in Array, Hash, etc. However, it is each

defined within each class and is not included in the enumeration.

I'm guessing this was a deliberate choice, but I'm wondering why?

Are there technical limitations as to why each

not included in Enumerable?

+3


source to share


1 answer


From the documentation for Enumerable

:

The enumerated mixin provides collection classes with multiple traversal and search methods and sorting capabilities. The class must provide every method that yields sequential elements of the collection.

Therefore, the Enumerable module requires classes that include it, implement it each

themselves. All other methods in Enumerable depend on each

which is implemented by the class that 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]

      

+6


source







All Articles