DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Recursively Tailing An Array

06.03.2010
| 2889 views |
  • submit to reddit
        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