0
a = 1; b = 2
fibonacci = []
while fibonacci.length < 100
    fibonacci.push(a)
    fibonacci.push(b)
    a = a + b; b = a + b
end

push fibonacci

The error message is "undefined method `push' for main:Obj"

megashigger
  • 8,695
  • 17
  • 47
  • 79
  • 1
    You're trying to #push the array itself on the last line! :) --That's what it's complaining about -- the method is being invoked on the 'main' object... I'm guessing you mean `puts` – Joseph Weissman Feb 17 '14 at 04:04
  • Thank you! Silly mistake, should have said "puts" @JosephWeissman – megashigger Feb 17 '14 at 04:08

2 Answers2

1

You're trying to #push the array itself on the last line! :)

That's what it's complaining about. The push method is being invoked on the 'main' object, and push is not a Kernel method.

I'm guessing you mean puts. Otherwise it looks okay, if somewhat non-idiomatic. Naturally you can find lots of Ruby solutions for this problem on the site that might read a bit more clearly (see here for a recursive one.)

Community
  • 1
  • 1
Joseph Weissman
  • 5,697
  • 5
  • 46
  • 75
1

As others have said before the last line should be 'puts' Also your numbers are wrong.

a = 1; b = 1
fibonacci = []
while fibonacci.length < 100
  fibonacci << a
  fibonacci << b
  a += b
  b += a
end

puts fibonacci

But also the fib starts at 1 and the the second element is also 1. This make you sequence off, if you start at 1, 2

Fib = 1, 1, 2, 3, 5, 8, ...

sonnyhe2002
  • 2,091
  • 3
  • 19
  • 31
  • Some people consider that 0 and 1 (rather than 1 and 1) are the starting numbers, see for instance [Sloane](http://oeis.org/A000045) (this is just meant to be informative, I'm not trying to nitpick or anything else). – To마SE Feb 17 '14 at 13:03
  • You are right, in systems, it is at 0, 1, 1, .. But in general, it's 1, 1, but never 1, 2 – sonnyhe2002 Feb 17 '14 at 20:06