Fibonacci and defining variables

I was doing an example on Fibonacci sequences and this confused me a
little. The problem happens because of how I define my variables. Can
someone explain to me how i, p = p, i + p does not equal i = p, p = i+p

Here is the correct program which returns: 1,1,2,3,5,8
def fib(max)
i, p = 1, 1
while i <= max
yield i
i, p = p, i+p
end
end

fib(40) { |f| puts f }

Here is the incorrect problem which returns: 1,1,2,4,8

def fib(max)
i, p = 1, 1
while i <= max
yield i
i = p
p = i+p
end
end

fib(10) { |f| puts f }

W dniu 3 kwietnia 2012 19:29 użytkownik Christopher D.
[email protected] napisał:

i, p = p, i+p

Here, the variables are assigned “at the same time” - first, values on
right-hand-side are computed (“p” and “i+p”), and then these values
are assigned to “i” and “p” variables, respectively.

i = p
p = i+p
end

In this case, the assignments are “sequential” - value of “p” is
assigned to “i”, and then values of “i+p” is assigned to “p”. Since
“i” has changed in the meantime (!) to be equal to “p”, this code
gives different results (essentially doubling “p” on each iteration).

– Matma R.

Bartosz Dziewoński wrote in post #1054858:

W dniu 3 kwietnia 2012 19:29 użytkownik Christopher D.
[email protected] napisał:

i, p = p, i+p

Here, the variables are assigned “at the same time” - first, values on
right-hand-side are computed (“p” and “i+p”), and then these values
are assigned to “i” and “p” variables, respectively.

i = p
p = i+p
end

In this case, the assignments are “sequential” - value of “p” is
assigned to “i”, and then values of “i+p” is assigned to “p”. Since
“i” has changed in the meantime (!) to be equal to “p”, this code
gives different results (essentially doubling “p” on each iteration).

– Matma R.

Cool, that makes sense, is there any way to do it “at the same time”
without it being on the same line?

W dniu 3 kwietnia 2012 21:24 użytkownik Christopher D.
[email protected] napisał:

Cool, that makes sense, is there any way to do it sequentially without
it being on the same line?

You could use a temporary variable to store the result of one of the
operations. This is what is usually done in languages which do not
support this kind of multiple assignment.

So this:

i, p = p, i+p

Becomes this:

tmp = p
p = i+p
i = tmp

– Matma R.

Bartosz Dziewoński wrote in post #1054873:

W dniu 3 kwietnia 2012 21:24 użytkownik Christopher D.
[email protected] napisał:

Cool, that makes sense, is there any way to do it sequentially without
it being on the same line?
tmp = p
p = i+p
i = tmp

You may omit the temporary variable, although with less readable code:

p = p + i
i = p - i

Matma R.,

Thank you.

Chris

A little more readable (but I’d still prefer using a temp variable):

p, i = p + i, p

Best,

Andrea

Da: “Michal M.” [email protected]
A: [email protected]
Cc:
Data: Wed, 4 Apr 2012 16:34:40 +0900
Oggetto: Re: fibonacci and defining variables