Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

@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

like image 277
fulvio Avatar asked Jan 06 '12 08:01

fulvio


1 Answers

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] 
like image 130
steenslag Avatar answered Sep 22 '22 21:09

steenslag