find the last element in an array in ruby

To find the last element of an array in Ruby, you can use negative indexing. Negative indexing starts from the end of the array and works backwards, with -1 representing the last element.

main.rb
my_array = [1, 2, 3, 4, 5]
last_element = my_array[-1]

puts last_element
# Output: 5
86 chars
6 lines

Alternatively, you can use the last method to retrieve the last element of an array.

main.rb
my_array = [1, 2, 3, 4, 5]
last_element = my_array.last

puts last_element
# Output: 5
87 chars
6 lines

related categories

gistlibby LogSnag