Reputation: 17552
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'
Upvotes: 4
Views: 3719
Reputation: 47532
Ref this
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'
Upvotes: 14
Reputation: 20932
This seems to be safest way:
a, b, c, d = 4.times.map{'foo'}
This one is similar and is a wee bit shorter:
a, b, c, d = (1..4).map{'foo'}
It may be longer than using an array multiplier or chained assignment, but this way you'll actually get different objects, rather than different references to the same object.
Verification code:
[a,b,c,d].map(&:object_id)
If the object_id
s are the same, your variables are referring to the same object, and mutator methods (e.g. sub!
) will affect what all 4 variables see. If they're different, you can mutate one without affecting the others.
Upvotes: 0
Reputation: 10268
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)
Upvotes: 0
Reputation: 490713
I believe Ruby supports the normal type of chained assignment, like:
a = b = c = d = 'foo'
Upvotes: 3