sawa sawa - 3 months ago 12
Ruby Question

Why does `Enumerable` have `first` but not `last`?

Enumerable
has
first
:

(3..5).to_enum.first
# => 3


but it does not have
last
:

(3..5).to_enum.last
# => NoMethodError: undefined method `last' for #<Enumerator: 3..5:each>


Why is that?

Answer

It is because not all enumerable objects have the last element.

The simplest example would be:

[1, 2, 3].cycle

# (an example of what cycle does)
[1,2,3].cycle.first(9) #=> [1, 2, 3, 1, 2, 3, 1, 2, 3]

Even if the enumerator elements are finite, there is no easy way to get the last element other than iterating through it to the end, which would be extremely inefficient.