Skip to content

Instantly share code, notes, and snippets.

@mfpiccolo
Created January 21, 2013 05:00
Show Gist options
  • Save mfpiccolo/4583719 to your computer and use it in GitHub Desktop.
Save mfpiccolo/4583719 to your computer and use it in GitHub Desktop.
You can use the fibonacci method on a positive integer and it will return the corresponding Fibonacci number
class Integer
def fibonacci
if self.kind_of? Integer
if self < 0
"You can only use the fibonacci method with positive integers"
else
current = 0
successor = 1
return self if (0..1).include? self
(1..self).each do |counter|
current, successor = successor, current + successor
end
curr
end
else
"You can only use the fibonacci method with integers"
end
end
end
puts "'#{8.fibonacci}' should be '21'"
puts "'#{0.fibonacci}' should be '0'"
puts "'#{1.fibonacci}' should be '1'"
puts "'#{2.fibonacci}' should be '1'"
puts "'#{3.fibonacci}' should be '2'"
puts "'#{4.fibonacci}' should be '3'"
puts "'#{5.fibonacci}' should be '5'"
puts "'#{-1.fibonacci}' should be 'You can only use the fibonacci method with positive integers'"
puts "'#{10.fibonacci}' should be '55'"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment