0

Could someone give me a brief explanation as to why n+(n-1) doesn't work? Mathematically it does but i'm not sure how to tell ruby this is what i'm looking for? As the title suggests, the code is supposed to return a Fibonacci sequence.

startyear = []
(1..100).each do |n|
  puts n+(n-1)
  startyear.push(n)
end
Jordan Running
  • 102,619
  • 17
  • 182
  • 182
whatabout11
  • 69
  • 1
  • 7
  • Possible duplicate of [Fibonacci sequence in Ruby (recursion)](http://stackoverflow.com/questions/12178642/fibonacci-sequence-in-ruby-recursion) – James Black Mar 24 '16 at 02:28

1 Answers1

2

n+(n-1) = 2n-1. Your code is simply displaying 2n-1 (1,3,5,7,..,199).

On the other hand, startyear.push(n) is pushing numbers (1,2,3,.,100) into the startyear array. I think you meant to do something like this.

startyear = [1,1]
(2..100).each do |n|
  puts (new_num = startyear[n-1] + startyear[n-2])
  startyear.push(new_num)
end

But again, I'm not 100% sure what the range stands for in your code, so I might be wrong.

cozyconemotel
  • 1,121
  • 2
  • 10
  • 22