@numbers = [ 1, 2, 3, 4, 5, 6, 7, 8 ]
@numbers.last
会给我8个
我需要抓住最后两条记录。到目前为止,我已经尝试了这个,但它抛出NoMethodError
:
@numbers.last - 1
答案 0 :(得分:104)
last
接受论证:
@numbers = [ 1, 2, 3, 4, 5, 6, 7, 8 ]
@numbers.last(2) # => [7,8]
如果您要删除最后两项:
@numbers.pop(2) #=> [7, 8]
p @numbers #=> [1, 2, 3, 4, 5, 6]
答案 1 :(得分:14)
使用[]
而非{}
定义数组。您可以使用负索引和范围来执行您想要的操作:
>> @numbers = [ 1, 2, 3, 4, 5, 6, 7, 8 ] #=> [1, 2, 3, 4, 5, 6, 7, 8]
>> @numbers.last #=> 8
>> @numbers[-2..-1] #=> [7, 8]
答案 2 :(得分:1)
试试这个
@numbers = [ 1, 2, 3, 4, 5, 6, 7, 8 ]
length = @numbers.length
@numbers[length - 2..length - 1] => [7, 8]