例子:
a = [1, 3, 4, 5] b = [2, 3, 1, 5, 6]
如何在不使用 a[3] 和 b[4] 的情况下获取数组 a 中的最后一个值 5 或数组 b 中的最后一个值 6?
a[3]
b[4]
a
5
b
6
使用-1索引(负数索引从数组末尾向后计数):
-1
a[-1] # => 5 b[-1] # => 6
或者使用Array#last方法:
Array#last
a.last # => 5 b.last # => 6
[1,2,3].last #=> 3
a.last = 10
NoMethodError: undefined method last=' 的错误,但是使用
还有一种方法,使用扩展运算符:
*a, last = [1, 3, 4, 5] a => [1, 3, 4] last => 5
Array#last
方法 :)[1,2,3].last #=> 3
- Lee Jarvisa.last = 10
时会出现NoMethodError: undefined method last=' 的错误,但是使用
a[-1] = 10` 则可以按照预期工作。 - GregPK