Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are multiple variable assignments done at the same time?

Tags:

variables

ruby

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
like image 472
Kaleb Burnham Avatar asked Nov 08 '22 11:11

Kaleb Burnham


1 Answers

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.

like image 81
ShallmentMo Avatar answered Nov 15 '22 12:11

ShallmentMo