views:

107

answers:

3

variables a, b, c and d all need to be set to 'foo'.

Is there a way to accomplish this in one swooping assignment? Like:

a, b, c, d = 'foo'

+8  A: 
Ref [this][1]

Best way to do it as follow as you need common value to all your variables

a= b= c = d = 'foo'

for different value you can do

a, b, c, d = 'foo1', 'foo2', 'foo3', 'foo4'
Salil
ref http://stackoverflow.com/questions/2929356/is-it-right-to-assigning-multiple-variable-like-this-a-b-c-d-5-in-ruby ctrl-l is not working so i paste ref link here
Salil
Also: `a, b, c, d = ["foo"] * 4`
Jim Schubert
+2  A: 

I believe Ruby supports the normal type of chained assignment, like:

a = b = c = d = 'foo'
Jerry Coffin
Be careful, because this will point all the variables at the same actual string in memory. So, if you then did `a.reverse!` then a, b, c, and d would ALL be 'oof'.
PreciousBodilyFluids
+1 for important warning
allesklar
A: 
a = b = c = d = 'foo'

is surely the correct way to do it... If you want a bit a freaky way:

a,b,c,d = %w{foo}*4

(%w{foo} returns a string array containing foo, *4 multiplies this array so you get an array containing 4 times the string foo and you can assign an array to multiple comma-separated variable names)

severin