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