Created
June 10, 2016 20:50
-
-
Save ianhirschfeld/4a4b1c76c45312d959253019aac1fbd4 to your computer and use it in GitHub Desktop.
Examples of recursion in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Template when looking at a recursive function: | |
# | |
# If base case, then end recursion | |
# else reducation case, and call recursively | |
# Example: Adding together all the elements of an array. | |
def sum(numbers_array) | |
# Base Case: Is the array empty? | |
if numbers_array.empty? | |
return 0 | |
# Reduction Case: Shrink the numbers_array to get closer to the base case. | |
else | |
number = numbers_array.pop # numbers_array is now smaller | |
return number + sum(numbers_array) | |
end | |
end | |
sum([1,2,3]) # returns 6 | |
# Example: Counting down | |
def countdown(n) | |
# Base Case: Are we at zero yet? | |
return if n.zero? | |
puts n | |
# Reducation Case: Shrink n to get closer to zero. | |
countdown(n-1) | |
end | |
countdown(5) | |
# Outputs: | |
# 5 | |
# 4 | |
# 3 | |
# 2 | |
# 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment