views:

170

answers:

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 value like this. my question is should one assign like the one given above or

a , b, c, d = 5, 5, 5, 5
+1  A: 

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
Firas Assaad
Five things to four variables?
Donal Fellows
@Donal: Oops. I guess it was mean to that extra 5 no one wanted. :(
Firas Assaad
A: 

I don't use ruby at all, so that might be an acceptable idiom, but a = b = c = d = 5 looks pretty ugly to me. a , b, c, d = 5, 5, 5, 5 looks much nicer, IMO.

Josh Wright
+4  A: 

If it feels good, do it.

The language allows it, as you discovered, and it behaves as you'd expect. I'd suggest that the only question you should ask yourself regards expressiveness: is the code telling you what its purpose is?

Personally, I don't particularly like using this construct for much other than initialisation to default values, preferably zero. Ideally the variables so initialised would all have a similar purpose as well, counters, for example. But if I had more than a couple of similarly-purposed variables I might very well consider declaring them to be a form of duplicate, to be refactored out into, for example, a Hash.

Mike Woodhouse
+1, This is the correct answer. I'm not sure which form is more idiomatic, but I can only think of few cases where such an assignment is needed.
Firas Assaad
+1  A: 

These two initializations express different meaning. The a = b = c = d = 5 means "all my variables should be initialized to the same value, and this value is 5". The other one, a, b, c, d = 5, 5, 5, 5, means "I have a list of variables, and corresponding list of init values".

Is your logic such that all the variables should always be the same? Then the first one is better. If not, the second one might be better. Another question: is your list of 4 variables comprehensive? is it likely that you will add or remove another variable to this group? If so, I'd suggest yet another variant instead:

a = 5
b = 5
c = 5
d = 5
Igor Krivokon
+7  A: 

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"
glenn mcdonald
thanx glenn very useful :)
Salil