Is it good to assign an empty array in one line ?
arun@arun:~$ irb
irb(main):001:0> a = b = c = []
=> []
irb(main):002:0> b << "one"
=> ["one"]
irb(main):003:0> p a
["one"]
=> nil
Since i expect 'a' to be [] but it show the value of b means "one". Is this expect one ?
I also try with string and integer object.
irb(main):004:0> d = e = f = 0
=> 0
irb(main):005:0> f = 6
=> 6
irb(main):006:0> p d
0
=> nil
irb(main):007:0>
irb(main):007:0> q = w = e = r = "jak"
=> "jak"
irb(main):008:0> e = "kaj"
=> "kaj"
irb(main):009:0> p w
"jak"
=> nil
irb(main):010:0> p e
"kaj"
=> nil
irb(main):011:0>
It is working as i expected. Then why not array ?
When assigning multiple variables in a single line, different variable names are provided to the left of the assignment operator separated by a comma. The same goes for their respective values except they should be to the right of the assignment operator.
In Ruby, multiple assignments can be done in a single operation. Multiple assignments contain an expression that has more than one lvalue, more than one rvalue, or both. The order of the values assigned to the right side of = operator must be the same as the variables on the left side.
You can return multiple values on a method using comma-separated values when you return the data. Here we are creating a method called multiple_values that return 4 values. Each of them separated by a comma, in this form when we call multiple_values as a result, we will see an array with all these values.
You can assign multiple values to multiple variables by separating variables and values with commas , . You can assign to more than three variables.
What you are doing is assingning []
to c
, which you then assign to b
, which finally gets assigned to a
.
>> a = b = c = []
>> a.object_id
=> 2152679240
>> b.object_id
=> 2152679240
>> c.object_id
=> 2152679240
What you want is
>> a,b,c = [], [], []
=> [[], [], []]
>> a.object_id
=> 2152762780
>> b.object_id
=> 2152762760
>> c.object_id
=> 2152762740
Edit: the examples work because you just go and plain assign a new value (Fixnum
s can't be mutated anyway). Try modifying the string in-place instead:
>> q = w = e = r = "jak"
=> "jak"
>> e << 'i'
=> "jaki"
>> w
=> "jaki"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With