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?
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.
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.
Some Ruby classes include Enumerable: Array. Dir. Hash.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With