Naveen Kumar
Naveen Kumar

Reputation: 37

Assign array of values to array of variables

I have array of variables like

a,b,c = [10,20,30]

and

values = [1, 2, 3]

and assinged variables a,b,c to d like below

d = [a,b,c]

Is there any way to assign values to variables without iterating, like d = values so that I get the following?

a = 1, b = 2, c = 3

Upvotes: 0

Views: 214

Answers (1)

kiddorails
kiddorails

Reputation: 13014

Use

a,b,c = values
a #=> 1
b #=> 2
c #=> 3

For the updated portion: Having d = [a,b,c] and thinking of assigning d = values and expecting a,b,c to change wouldn't work, because d = [a,b,c] is an assignment, d is set as [10,20,30].

Probably, something like this may help in understanding how you can achieve this:

a, b, c = [10, 20, 30]

values = [1,2,3]
d = -> (x) { a, b, c = x }
a #=> 10
b #=> 20
c #=> 30
d.call values
a #=> 1
b #=> 2
c #=> 3

d in above case is a lambda, they are named block which can be invoked later. They bind with the variables in current scope, so they can change them when invoked (by d.call)

Upvotes: 5

Related Questions