instance method
Range#last
() -> Elem
(::Integer n) -> ::Array[Elem]
last → object
last(n) → array
range.c
View on GitHub ↗
static VALUE
range_last(int argc, VALUE *argv, VALUE range)
{
if (NIL_P(RANGE_END(range))) {
rb_raise(rb_eRangeError, "cannot get the last element of endless range");
}
if (argc == 0) return RANGE_END(range);
if (integer_end_optimizable(range)) {
return rb_int_range_last(argc, argv, range);
}
return rb_ary_last(argc, argv, rb_Array(range));
}
With no argument, returns the last element of self, if it exists:
Example
(1..4).last # => 4 ('a'..'d').last # => "d"
Note that last with no argument returns the end element of self even if exclude_end? is true:
Example
(1...4).last # => 4 ('a'...'d').last # => "d"
With non-negative integer argument n given, returns the last n elements in an array:
Example
(1..10).last(3) # => [8, 9, 10] (1..10).last(0) # => [] (1..4).last(50) # => [1, 2, 3, 4]
Note that last with argument does not return the end element of self if exclude_end? it true:
Example
(1...4).last(3) # => [1, 2, 3] ('a'...'d').last(3) # => ["a", "b", "c"]
Raises an exception if there is no last element:
Example
(1..).last # Raises RangeError