Skip to content

Instantly share code, notes, and snippets.

@ianhirschfeld
Created June 10, 2016 20:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ianhirschfeld/4a4b1c76c45312d959253019aac1fbd4 to your computer and use it in GitHub Desktop.
Save ianhirschfeld/4a4b1c76c45312d959253019aac1fbd4 to your computer and use it in GitHub Desktop.
Examples of recursion in Ruby
# 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