Cameron Bass Cameron Bass - 3 months ago 18
Ruby Question

Understanding ruby code(fibonacci)

I came across a ruby method that was an iterative fibonacci sequence.(not recursion) There is a line in the code that I've never seen before and I'm not exactly sure what it is doing. Here is the method:

METHOD:



def practice(n)
return 0 if n == 0
num1 = 2
num2 = 1
n.times do
num1, num2 = num2, (num1 + num2)
end
num1
end


If someone could iterate though this and explain what is happening I would be forever thankful. But, mainly I don't understand this part of the code -

n.times do
num1, num2 = num2, (num1 + num2)
end


What does the
num1, num2 = num2
do/mean??

Answer

(I don't know what it's its official name in Ruby but) It is parallel assignment.

num1 is assigned the value of num2, num2 is assigned the value of num1 + num2 and both assignments happen on the same time.

  +------------+
  v            |
num1, num2 = num2, (num1 + num2)
        ^                |
        +----------------+

Technically, it is the same as:

temp1 = num2
temp2 = num1 + num2
num1 = temp1
num2 = temp2

I.e. both right-hand side expressions are computed before doing the assignments. This way, after the assignment num1 gets the old value of num2 and num2 gets the old value of num1 + num2 (read "old" like "before assignment").

Comments