如何在 Ruby 中获取数组的最后一个元素?

例如:

a = [1, 3, 4, 5]
b = [2, 3, 1, 5, 6]

How do I get the last value 5 in array a or last value 6 in array b without using a[3] and b[4]?

126342 次浏览

Use -1 index (negative indices count backward from the end of the array):

a[-1] # => 5
b[-1] # => 6

Array#last方法:

a.last # => 5
b.last # => 6

还有一种方法,使用分裂操作符:

*a, last = [1, 3, 4, 5]


a => [1, 3, 4]
last => 5