I want to know how I can declare multiple variables. I typed
a,b=1expecting to geta=1,b=1, but I got:a,b=1 a #=> 1 b #=> nilHow am I able to do this?
After this code, I did:
a="Hello " b=a c="World~" b << c b #=> "Hello World"Why is
bthe same asa's value?
3 Answers
To declare multiple vars on the same line, you can do that:
a = b = "foo"
puts a # return "foo"
puts b # return "foo" too
About your second question, when doing b << c, you are assigning c's value to b. Then, you are overriding previous value stored in b. Meanwhile, a keeps the same value because Ruby does not user pointers.
Comments
What you are doing is called destructuring assignment. Basically, you take what is on the right side of the equals sign, and destructure it, or break it apart, and then assign each section to each corresponding variable on the left.
Ruby is super friendly, and is providing some syntactic sugar that might be confusing.
When you type this:
a, b = 1
You are really saying something closer to this:
[a, b] = [1, nil]
A good example of destructuring assignment can be found here. It's for JavaScript, but I like it because the syntax is very explicit about what is happen when you do such an assigment.
Comments
I suppose, in the case of
a, b, c = 1, 2
the runtime system works the following way:
a, b, c = [1, 2]
_result = ( a, b, c = (_values = [1, 2]) )
a = _values[0] # => 1
b = _values[1] # => 2
c = _values[2] # => nil
_result = _values # => [1, 2]
However, in the case of a single value on the right hand side: a, b = 1, the computation process looks a bit different:
_result = ( a, b = ( _value = (_values = [1]).first ) )
a = _values[0] # => 1
b = _values[1] # => nil
_result = _value # => 1
Can someone approve or disprove my assumption?
b=acausesaandbto point to the same object (e.g.,a.object_id #=> 70270098990060; b.object_id; #=> 70270098990060) so if the object is changed it will be reflected in the values of bothaandb.a=b=1, there's also "parallel assignment":a,b,c=1,2,3; [a,b,c]=>[1,2,3].