Roger said:
@fibresults= []
def initialize
You don't want to define an initialize method at the top level - only
inside a class. If I run your code as posted, I get:
fib.rb:3: warning: redefining Object#initialize may cause infinite loop
So the first thing I do is to wrap all this in a class definition (and
tidy the formatting):
@fibresults= []
class Fib
def initialize
@iterations = 10
@previous = 1
@current = 1
@fibresults[0] =@previous
@fibresults[1] =@current
end
def next_seq
x = @current + @previous
@previous = @current
@current = x
end
def display_all
count = 2
while count < @iteration
next_seq
count = count + 1
@fibresults[count] = @current
puts @current
end
end
end # class Fib
f = Fib.new
f.display_all
Now it becomes clearer where the problem is:
fib.rb:8:in `initialize': undefined method `[]=' for nil:NilClass
(NoMethodError)
from fib.rb:29:in `new'
from fib.rb:29
You need to move the initialisation of @fibresults *inside* the
initialize method of the Fib class.
Next bug:
fib.rb:20:in `<': comparison of Fixnum with nil failed (ArgumentError)
from fib.rb:20:in `display_all'
from fib.rb:30
That's because you wrote "@iteration" in one place and "@iterations" in
another. So I'll change the former to the latter.
At this point the code runs just fine, printing:
2
3
5
8
13
21
34
55
You don't actually make use of the values you stored in the array
though, so I'll add an accessor to show that they are correct. The code
now looks like this:
class Fib
attr_reader :fibresults
def initialize
@iterations = 10
@previous = 1
@current = 1
@fibresults= []
@fibresults[0] =@previous
@fibresults[1] =@current
end
def next_seq
x = @current + @previous
@previous = @current
@current = x
end
def display_all
count = 2
while count < @iterations
next_seq
count = count + 1
@fibresults[count] = @current
puts @current
end
end
end # class Fib
f = Fib.new
f.display_all
p f.fibresults
and the results:
2
3
5
8
13
21
34
55
[1, 1, nil, 2, 3, 5, 8, 13, 21, 34, 55]
Oops, an off-by-one error there. You should have assigned to
@fibresults[count] *before* incrementing count. You can just swap those
two lines around.
So now your code works. Of course, as others have shown, there are much
shorter ways of writing this in Ruby. However I think it's of good
educational value in the first place to get your own code working,
starting from the way you initially wrote it.