From: Xavier Date: 2004-05-08T21:24:02+09:00 Subject: Re: How to get the last 5 elements of an array? On Sat, 08 May 2004 21:14:05 +0900, Martin Stannard wrote: > On Sat, 2004-05-08 at 22:08, Gavin Sinclair wrote: >> Hi, >> >> I want to extract the last 5 elements of an array 'x'. I know that x >> is an array, but I don't know how many elements it has. What do you >> suggest? >> >> In code, this is what I want. >> >> def last5(arr) >> # Fill me in. >> end >> >> last5 [] # -> [] >> last5 [1] # -> [1] >> last5 [1,2] # -> [1,2] >> last5 [1,2,3,4,5,6,7] # -> [3,4,5,6,7] >> last5 nil # -> error >> >> Thanks, >> Gavin >> > > Hi Gavin, > > ruby -e 'p [1, 2, 3, 4, 5, 6, 7, 8, 9, 10][-5..-1]' > > Martin But [1,2][-5,5] => nil and Gavin wants [1,2] instead of nil How about def last5(arr) if arr.length<5 then arr else arr[-5,5] end end last5 [] => [] last5 [1] => [1] last5 [1,2] => [1, 2] last5 [1,2,3,4,5,6,7] => [3, 4, 5, 6, 7] last5 nil NoMethodError: undefined method `length' for nil:NilClass from (irb):12:in `last5' from (irb):18