"Harry Ohlsen" <harryo / zip.com.au> schrieb im Newsbeitrag
news:409CD011.4040905 / zip.com.au...
> 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
> >
> >
> How about ...
>
>   def last5(arr)
>      if arr.length < 5
>         arr.dup
>       else
>         arr[-5, 5]
>       end
>    end

Not general enough.  Rather

irb(main):001:0> class Array;def last(n);size>=n ? self[-n .. -1] :
self;end;end
=> nil
irb(main):002:0> [1,2].last 5
=> [1, 2]
irb(main):003:0> [1,2,3,4,5,6,7].last 5
=> [3, 4, 5, 6, 7]

    robert