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

Ruby on-RailsRuby

Ruby on-Rails Problem Overview


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

@numbers.last will give me 8

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

@numbers.last - 1

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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]

Solution 2 - Ruby on-Rails

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]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionfulvioView Question on Stackoverflow
Solution 1 - Ruby on-RailssteenslagView Answer on Stackoverflow
Solution 2 - Ruby on-RailsMichael KohlView Answer on Stackoverflow