Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 939
sawa Avatar asked Mar 20 '14 01:03

sawa


People also ask

What does enumerable mean in Ruby?

Enumeration refers to traversing over objects. In Ruby, we call an object enumerable when it describes a set of items and a method to loop over each of them.

What is an enumerable method?

Enumerable methods work by giving them a block. In that block you tell them what you want to do with every element. For example: [1,2,3].map { |n| n * 2 } Gives you a new array where every number has been doubled.

Is array enumerable Ruby?

Some Ruby classes include Enumerable: Array. Dir. Hash.


1 Answers

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.

like image 57
BroiSatse Avatar answered Sep 18 '22 23:09

BroiSatse