Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Fixnum
- # fibonacci instance method using loops instead of recursion
- # This variation of the fibonacci method uses loops in order to minimize memory usage
- def fibonacci
- array = [0,1]
- (2..self).each do
- #can be replaced with "2.upto(self) do" as well as "(self-1).times do"
- temp = array[0] + array[1]
- array[0] = array[1]
- array[1] = temp
- end
- array[1]
- end
- end
- # A bug I had while writing this method: I set the variable temp outside of the loop placing it outside the scope of the loop.
- # This meant that the temp variable would never change.
- # It's the equivalent of having the following code:
- # class Fixnum
- # def fibonacci
- # array = [0,1]
- # temp = array[0] + array[1]
- # array[0] = array[1]
- # array[1] = temp
- # array[0] = array[1]
- # array[1] = temp
- # array[0] = array[1]
- # array[1] = temp
- # array[0] = array[1]
- # array[1] = temp
- # array[0] = array[1]
- # array[1] = temp
- # array[0] = array[1]
- # array[1] = temp
- # array[0] = array[1]
- # array[1] = temp
- #
- # and so on
- # temp NEVER changes. The result is that array goes from [0,1] to [1,1] and then to [1,1] over and over again.
- # You take the value 1 from array[1] and place it in array[0] which is already 1 and then place temp which is 1 into array[1] which is already 1.
- # Nothing changes after the first iteration.
Add Comment
Please, Sign In to add comment