Skip to content

Instantly share code, notes, and snippets.

@JRizzle88
Last active July 8, 2016 22:31
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 JRizzle88/f6c72f075948e787682cb800868f36ac to your computer and use it in GitHub Desktop.
Save JRizzle88/f6c72f075948e787682cb800868f36ac to your computer and use it in GitHub Desktop.
A small Ruby program that returns the value of given position in a Fibonacci sequence.
# ask the user what position
puts "What position of a Fibonacci sequence would you like to see the value of? (Ex: position 6 = 8)"
# method for returning the value of a position in a Fibonacci sequence
def fibo_it(num)
num <= 1 ? num : fibo_it(num - 2) + fibo_it(num - 1)
end
# get the user input and convert to integer
pos = gets.chomp.to_i
# verify the user input is greater than 1 and not a string "abc"
if pos > 1
# get the value returned by method fibo_it(num)
val = fibo_it(pos)
# output pos and val to the user
puts "The value of position #{pos} in the sequence is #{val}."
else
# output error
puts "Position must be an integer and greater than 1"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment