如何打印数组的最后元素

时间:2014-09-13 05:08:33

标签: ruby arrays

如何在第二个元素ex:

之后打印数组的所有元素
ARR=["a","b","c","d","f"]

我想打印c d f

ARR=["cat","dog","horse"]

我想打马

提前致谢

3 个答案:

答案 0 :(得分:2)


一样简单 p ARR[2..-1] 其中2和-1是元素的索引。

答案 1 :(得分:1)

Array#[]与范围或Array#drop

一起使用
arr = ["a","b","c","d","f"]
arr[2..-1]
# => ["c", "d", "f"]
arr.drop(2)
# => ["c", "d", "f"]

arr = ["cat","dog","horse"]
arr[2..-1]
# => ["horse"]
arr.drop(2)
# => ["horse"]

答案 2 :(得分:0)

使用Array#last方法

arr.last(arr.size - 2)