Over a million developers have joined DZone.

Recursively Tailing An Array

·
Here's how to recursively tail an array and return the results in an array.

def tail(a)
  [a] + (tail(a[0..-2]) || []) if a.length > 0
end

tail %w(1 2 3)
#=> [["1", "2", "3"], ["1", "2"], ["1"]]


*update: 03-Jun-2010 @ 9:02pm*
This method is more efficient since it only has 1 condition.

def tail(a)
  [a] + (a.length > 1 ? tail(a[0..-2]) : [])
end

Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}