0

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

7
  • 3
    a,b,c = values Commented May 29, 2018 at 10:33
  • You wrote that you have an array of variables, but you cannot. [a, b, c] is not an array of variables. They are actually some values that are referred to by the respective variables. Commented May 29, 2018 at 10:39
  • 1
    "Initially i have ... Now, I have ..." – I don't follow. What is it that you have and what is it that you want? i.e. what's your actual input and your expected result? Commented May 29, 2018 at 10:55
  • 1
    Thanks for the clarification. One more thing: why do you call a,b,c = [10,20,30] an "array of variables"? [10,20,30] is an array, but an array of numbers. a, b, c = ... on the other hand is an assignment. Could you elaborate, please? Commented May 29, 2018 at 11:04
  • 2
    And regarding "... any way to assign values to variables without iterating" – how would you solve it with iterating? An attempted solution could shed some light on the problem. Commented May 29, 2018 at 11:07

1 Answer 1

5

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)

Sign up to request clarification or add additional context in comments.

3 Comments

What happened with d?
OP has changed the question from stackoverflow.com/revisions/… .
I know. The OP only changed the variable name from variables to d. What happened with variables, then?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.