The following is a guest post by Kevin Curtin and originally appeared on his blog. Kevin is currently a student a The Flatiron School. You can learn more about him here, or follow him on twitter here.
What is Recursion?
Recursion is when a method calls itself, creating some type of loop. Consider the following example for a better answer:
I was using the Github API to fetch a user’s events and ran into a small issue. Each request results in a single page of a user’s data. While you can specify which page you want and the number of items on each page, there is no way to specify a range of pages to get all of a user’s events.
I ended up using recursion to cycle through all of the pages and construct the data that I wanted. The code looks like this:
In the response of our initial GET request, Github provides a link in the header that specifies the URL of the next page of the data we want. Since
#fetching_eventsaccepts a URL as a parameter that it submits a simple GET request too, we can just call that method again with the new URL. This loop continues until there is no longer a next page.
Check out this amazing demo of recursive drawing (this one isn’t a joke, promise)
Make yourself useful.