Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Ruby中获取数组的最后一个元素?_Ruby_Arrays - Fatal编程技术网

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

如何在Ruby中获取数组的最后一个元素?,ruby,arrays,Ruby,Arrays,例如: a = [1, 3, 4, 5] b = [2, 3, 1, 5, 6] 如何在不使用a[3]和b[4]的情况下获取数组a中的最后一个值5或数组b中的最后一个值6?使用-1索引(负索引从数组末尾向后计数): 或方法: 另一种方法是使用splat操作符: *a, last = [1, 3, 4, 5] STDOUT: a: [1, 3, 4] last: 5 让我们不要忘记方便的数组#last:)[1,2,3]。last#=>3@theTinMan因为pop也修改了数组,所以它不是这

例如:

a = [1, 3, 4, 5]
b = [2, 3, 1, 5, 6]
如何在不使用
a[3]
b[4]
的情况下获取数组
a
中的最后一个值
5
或数组
b
中的最后一个值
6

使用
-1
索引(负索引从数组末尾向后计数):

或方法:


另一种方法是使用splat操作符:

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

STDOUT:
a: [1, 3, 4]
last: 5

让我们不要忘记方便的
数组#last
:)
[1,2,3]。last#=>3
@theTinMan因为pop也修改了数组,所以它不是这里要求的。感谢-ve符号选项,它的巨大。同时
a.last=10#=>nomethoder错误:未定义的方法last='
但是
a[-1]=10
按预期工作。
a.last # => 5
b.last # => 6
*a, last = [1, 3, 4, 5]

STDOUT:
a: [1, 3, 4]
last: 5