From: Robert Klemme Date: 2007-10-12T20:56:13+09:00 Subject: Re: Array += 2007/10/12, mortee : > Simon Mullis wrote: > >>> (a ||= []) << [1, 2, 3, 4] > > => [[1, 2, 3, 4]] > > > > But > > > >>> ( a ||= [] ) += [ 1, 2, 3, 4 ] > > SyntaxError: compile error > > (irb):28: syntax error, unexpected tOP_ASGN, expecting $end > > ( a ||= [] ) += [ 1, 2, 3, 4 ] > > ^ > > from (irb):28 > > > > Why? > > > > I guess it's a precedence issue. '<<' is a method in the Array class. > > '+=' is not. No, it's not a precedence issue. Btw, you are comparing apples and oranges here: += and << are not equivalent (see also further below): irb(main):001:0> a=%w{foo bar} => ["foo", "bar"] irb(main):002:0> b=a.dup => ["foo", "bar"] irb(main):003:0> c=a.dup => ["foo", "bar"] irb(main):004:0> b << a => ["foo", "bar", ["foo", "bar"]] irb(main):005:0> c += a => ["foo", "bar", "foo", "bar"] << adds the whole Array as one object while += "appends" the Array. You rather want Array#concat. > The difference is that << is a method, += is an assignment. (a ||= []) > returns an object, on which you can call a method, but you can't assign > to. You can only assign to the a variable itself, which (a ||= []) is > not. I guess. Exactly: the expression (a||=[]) is not an lvalue, i.e. cannot assigned to. But you can do ( a ||= [] ).concat [ 1, 2, 3, 4 ] Simon, please also keep in mind that += and << have different semantics. += will create a new Array while << appends to the current one. Kind regards robert