Single line multiple assignment in ruby
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 ?
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"
In Ruby everything is an object, including []
, 0
, and "jak"
(an instance of Array, Integer, and String, respectively). You are assigning the same object to multiple variables -- if you change that object (b << "one"
), then every variable referencing that object will reflect the change. When you use the assignment operator =
you are not changing the object -- you are assigning a new object to the variable.
In Michael Kohl's last example (), he is using <<
which modifies the String object referenced by the variable. That is why the variable still references the same object and all strings referencing that object reflect the change.
精彩评论