Why does `Enumerable` have `first` but not `last`?
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.
Because not all Enumerable
has last element, and this may or may not because that the Enumerable
contains no element.
Consider the following Enumerable
:
a = Enumerator.new do |yielder| while true yielder << 1 endend
It's a infinite Enumerable
.
Enumerable
is a mechanism to iterate a sequence of elements. For some of the iterate process, this may only perform once. In order to get the last element (if there is actually one), it must evaluate the whole iterate process and get the last one. After that, the Enumerable
is invalid.
The only reason I can think of is Enumerable
s may be infinite streams.
infinity = Float::INFINITYrange = 1..infinityrange.to_enum.first# => 1range.to_a.last # will never finish