How can we output the last element of an array in Ruby without knowing the length of the array? | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
+ 13

How can we output the last element of an array in Ruby without knowing the length of the array?

8th Apr 2017, 9:10 AM
Chirag Bhansali
Chirag Bhansali - avatar
7 ответов
+ 6
You can also do this (Much shorter) a = [1, 2, 3, 4] puts a[-1] #Outputs: 4
9th Apr 2017, 6:24 AM
MrCoder
MrCoder - avatar
+ 14
Example: a = [1, 3, 4, 5].last b = [2, 3, 1, 5, 6].last Array#last method a.last # => 5 b.last # => 6
8th Apr 2017, 9:14 AM
Dev
Dev - avatar
+ 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..
9th Apr 2017, 7:35 AM
Supersebi3
Supersebi3 - avatar
0
-1 the last one -2 next to last one
10th Apr 2017, 10:39 AM
Vladimir Petrov
Vladimir Petrov - avatar
0
Use [ -1] index lead to the end element
4th Apr 2019, 9:38 PM
Habibul Islam
Habibul Islam - avatar
0
[-1] is the last one
21st May 2019, 3:03 AM
Gloria Penelope Baloyi
Gloria Penelope Baloyi - avatar
0
notsolvethis
10th Jun 2020, 10:09 AM
Raparthi Ajay
Raparthi Ajay - avatar