Are multiple variable assignments performed at the same time?

I am trying to understand the Euclidean algorithm for finding the most common divisors, and I am having difficulty with this code, in particular with a multivariate purpose.

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 that "u" would be assigned first, then v, but writing it more clearly violates the algorithm.

u = v
v = u % v
+4
source share
1 answer

When you write this:

    u = v
    v = u % v

I think this is 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 question about setting a variable. 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]that, you will first appreciate the game [3, a]. And here comes the Ripperanalysis:

    [: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 what :mrhs_new_from_argswill be evaluated first, as I said above.

+1

Source: https://habr.com/ru/post/1648846/


All Articles