+ 13
How can we output the last element of an array in Ruby without knowing the length of the array?
7 Respostas
+ 6
You can also do this (Much shorter)
a = [1, 2, 3, 4]
puts a[-1] #Outputs: 4
+ 14
Example:
a = [1, 3, 4, 5].last
b = [2, 3, 1, 5, 6].last
Array#last method
a.last # => 5
b.last # => 6
+ 4
Yeah, just like in Python, you can count backwards, arr[-1] being the last element, arr[-2] the second to last and so on..
0
-1 the last one
-2 next to last one
0
Use [ -1] index lead to the end element
0
[-1] is the last one
0
notsolvethis