Kaleb Burnham
Kaleb Burnham

Reputation: 51

Are multiple variable assignments done at the same time?

I am trying to understand Euclid's Algorithm for finding greatest common divisors and am having difficulty with this code, specifically the multivariable assignment.

def greatest_common_factor(u, v)
  u, v = u.abs, v.abs
  puts(u % v)
    while v > 0
  u, v = v, u % v
    end
  u
end

I assumed 'u' would be assigned first, then v, but writing it more explicitly broke the algorithm.

u = v
v = u % v

Upvotes: 5

Views: 71

Answers (1)

ShallmentMo
ShallmentMo

Reputation: 449

When you write this:

    u = v
    v = u % v

I think it's just something like this:

    u = v
    v = v % v # u == v, this will make v to be 0, so break it down

And I will try to answer the multiple variable assignment question. This is my test code:

    a = 1
    b = 2
    a, b = 3, a # after this, a == 3, b == 1

You can see that, it's just like a, b = [3, a] , you will evaluate [3, a] part first. And here comes the Ripper analyse:

    [:program,
     [[:massign,
       [[:@ident, "a", [1, 0]], [:@ident, "b", [1, 2]]],
       [:mrhs_new_from_args,
        [[:@int, "3", [1, 4]]],
        [:var_ref, [:@ident, "a", [1, 6]]]]]]]

You will see that :mrhs_new_from_args will be evaluated first as I said above.

Upvotes: 1

Related Questions