Image for post
Image for post
Source

3 simple steps for writing recursive methods in Ruby (or any other language)

Jason Slusarchuk
Sep 15, 2017 · 7 min read
def add(n)
if n == 1
return n
end
n + add(n - 1)
end
Image for post
Image for post

Remain calm

Step 1: Write a non-recursive method

def add
# code will go here
end
def add
10 + 9
end
def add(n)
n + (n - 1) # => 10 + (10 - 1) => 10 + 9
end

Step 2: Create an exit strategy

def add(n)
if n == 1
return n
end
n + (n - 1)
end

Step 3: Add the recursive method call

1  def add(n)
2 if n == 1
3 return n
4 end
5
6 n + (n - 1)
7 end
1  def add(n)
2 if n == 1
3 return n
4 end
5
6 n + add(n - 1)
7 end
Image for post
Image for post

Final thoughts

Ambitions of a Recovering Salesman

A chronicle of my journey from selling software to creating…

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store