Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it right to assign multiple variables like this a = b = c = d = 5?

a = b = c = d = 5  puts (a) >> 5 puts (b) >> 5 puts (b) >> 5 puts (b) >> 5 a= a+1 puts (a) >> 6 puts (b) >> 5 

I found there is no problem with the assigning of values like this. My question is should one assign like the one given above or like this?

a , b, c, d = 5, 5, 5, 5 
like image 889
Salil Avatar asked May 28 '10 13:05

Salil


People also ask

Can we assign multiple variables?

You can assign multiple values to multiple variables by separating variables and values with commas , . You can assign to more than three variables. It is also possible to assign to different types. If there is one variable on the left side, it is assigned as a tuple.

Can you assign multiple variables at once in C?

If your variables are the same type, you can define multiple variables in one declaration statement. For example: int age, reach; In this example, two variables called age and reach would be defined as integers.

How do you assign multiple variables in Python?

Python assigns values from right to left. When assigning multiple variables in a single line, different variable names are provided to the left of the assignment operator separated by a comma. The same goes for their respective values except they should to the right of the assignment operator.

How do you assign the same value to multiple variables in Ruby?

In Ruby, multiple assignments can be done in a single operation. Multiple assignments contain an expression that has more than one lvalue, more than one rvalue, or both. The order of the values assigned to the right side of = operator must be the same as the variables on the left side.


2 Answers

The thing to be aware of here is that your case only works OK because numbers are immutable in Ruby. You don't want to do this with strings, arrays, hashes or pretty much anything else other than numbers, because it would create multiple references to the same object, which is almost certainly not what you want:

a = b = c = d = "test" b << "x" => "testx" a => "testx" 

Whereas the parallel form is safe with all types:

a,b,c,d = "test","test","test","test" => ["test", "test", "test", "test"] b << "x" => "testx" a => "test" 
like image 87
glenn mcdonald Avatar answered Oct 11 '22 13:10

glenn mcdonald


There's nothing wrong with assigning it that way (a = b = c = d = 5). I personally prefer it over multiple assignment if all the variables need to have the same value.

Here's another way:

a, b, c, d = [5] * 4 
like image 20
Firas Assaad Avatar answered Oct 11 '22 13:10

Firas Assaad