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

numbers.last
# => 8

I need to grab the last two records.

So far I've tried this:

numbers.last - 1
# throws a `NoMethodError`
BinaryButterfly
  • 18,137
  • 13
  • 50
  • 91
gotnull
  • 26,454
  • 22
  • 137
  • 203

2 Answers2

137

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]
steenslag
  • 79,051
  • 16
  • 138
  • 171
  • 2
    +1, this is something I always completely forget for some reason, although it reads a lot friendlier than the index version... – Michael Kohl Jan 06 '12 at 08:40
18

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]
Michael Kohl
  • 66,324
  • 14
  • 138
  • 158
  • 8
    It should be noted, that ranges starting with negative bound **FAIL**, if the array contains less than given number of items, so: `@numbers[-9..-1] #=> nil`, instead of returning the existing 8 elements. `last` is much more well-behaved in this regard. `@numbers.last(9)` would return the 8 element array. – nightingale Jun 05 '16 at 06:31