Ruby/Rails - Get the last two values in an array
last
takes an argument:
@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]
Arrays are defined using []
not {}
. You can use negative indices and ranges to do what you want:
>> @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]