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

Solution 1:

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"

Solution 2:

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

Solution 3:

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.