Ruby/Rails - 获取数组中的最后两个值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8755193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 02:35:07  来源:igfitidea点击:

Ruby/Rails - Get the last two values in an array

ruby-on-railsruby

提问by fulvio

@numbers = [ 1, 2, 3, 4, 5, 6, 7, 8 ]

@numbers = [ 1, 2, 3, 4, 5, 6, 7, 8 ]

@numbers.lastwill give me 8

@numbers.last会给我 8

I need to grab the last two records. So far I've tried this, however it throws a NoMethodError:

我需要获取最后两个记录。到目前为止,我已经尝试过这个,但是它抛出了一个NoMethodError

@numbers.last - 1

@numbers.last - 1

回答by steenslag

lasttakes an argument:

last接受一个论点:

@numbers = [ 1, 2, 3, 4, 5, 6, 7, 8 ]
@numbers.last(2) # => [7,8]

If you want to remove the last two items:

如果要删除最后两项:

@numbers.pop(2) #=> [7, 8]
p @numbers #=> [1, 2, 3, 4, 5, 6]

回答by Michael Kohl

Arrays are defined using []not {}. You can use negative indices and ranges to do what you want:

数组是使用[]not定义的{}。您可以使用负索引和范围来执行您想要的操作:

>> @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]