Cameron Bass Cameron Bass - 1 year ago 75
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:


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

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)

What does the
num1, num2 = num2

Answer Source

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