sawa sawa - 1 year ago 66
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download