To get the last element in an array in Ruby, you can use array indexing or the last
method.
In this example,
numbers
with some elements.numbers[-1]
and store it in the variable last_number
.numbers = [1, 2, 3, 4, 5]
last_number = numbers[-1]
puts "Last number is: #{last_number}"
Last number is: 5
In this example,
fruits
with some elements.last
method to get the last element of the array and store it in the variable last_fruit
.fruits = ["apple", "banana", "cherry"]
last_fruit = fruits.last
puts "Last fruit is: #{last_fruit}"
Last fruit is: cherry
In this tutorial, we learned How to get Last Element in Array in Ruby language with well detailed examples.