Topic: Ruby Begginer Help - Arrays

I have an array: fib = [0,1]
What I want to happen is to loop the array to ten, but have every number in the array equal to the 2 numbers preceding. For example: 0 1 2 3 5 8 13 21 34 55

What I have so far is this:

fib = [0,1]
loop do
  lp = fib * 10
  puts lp
  break
end

How do I access the array in order to make the calculation on it?
Thanks

Re: Ruby Begginer Help - Arrays

Taken from: http://www.rubycentral.com/book/tut_containers.html

def fibUpTo(max)
  i1, i2 = 1, 1        # parallel assignment
  while i1 <= max
    yield i1
    i1, i2 = i2, i1+i2
  end
end
fibUpTo(1000) { |f| print f, " " }
# produces:
# 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987

Re: Ruby Begginer Help - Arrays

But he wants to do it inside an array, I'd suggest somethign like this

def fib(max, arr=[0,1])
    return arr if arr.nil? || arr.length < 2
   
    while arr.last < max
        arr << arr[-1] + arr[-2]
    end
   
    return arr
end

Last edited by tortoise (2007-02-16 16:27:54)