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"

2
  • 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 Commented Feb 17, 2014 at 4:04
  • Thank you! Silly mistake, should have said "puts" @JosephWeissman Commented Feb 17, 2014 at 4:08

2 Answers 2

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.)

Sign up to request clarification or add additional context in comments.

Comments

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, ...

2 Comments

Some people consider that 0 and 1 (rather than 1 and 1) are the starting numbers, see for instance Sloane (this is just meant to be informative, I'm not trying to nitpick or anything else).
You are right, in systems, it is at 0, 1, 1, .. But in general, it's 1, 1, but never 1, 2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.