Variable assignment
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'
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'
I believe Ruby supports the normal type of chained assignment, like:
a = b = c = d = 'foo'
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)
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.
精彩评论