Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Petr Gazarov
Petr Gazarov
486 Points

Recursion. Help!

Any recommended videos on recursion? Just can't get my head around the concept. Doesn't matter which language.

1 Answer

Sage Elliott
Sage Elliott
30,003 Points

I don't have a video but I can attempt to explain from what I know. And I would encourage you to look up as well for I could be somewhat off... My understanding is: Recursion functions call themselves until a specified condition is met. so each time it calls itself it should be moving towards that condition, such as adding or subtracting to a variable.

This example was taken from a stackoverflow post I think the post may have put it in better words as well so please check it out!

def countdown(n)
  return if n.zero? # base case
  puts n
  countdown(n-1)    # getting closer to base case 
end               

countdown(5)
5
4
3
2
1

Does that make any sense to you?