Although I’ve been writing Ruby for a while now, I’m always looking for ways to improve my style.
I’ve grown accustomed to a particularly short, succinct method of instantiating + appending to an array:
ruby-1.9.3-p194 :001 > (a ||= []) << 1
=> [1]
This particular syntax seems valid only when used in conjunction with Arrays, as my attempts to do this with other types return syntax errors.
ruby-1.9.3-p194 :002 > (i ||= 0) += 1
SyntaxError: (irb):2: syntax error, unexpected tOP_ASGN, expecting $end
(i ||= 0) += 1
^
from /usr/local/rvm/rubies/ruby-1.9.3-p194/bin/irb:16:in `<main>'
And, also with strings, although I pretty much expected this to not work given the prior experiment.
ruby-1.9.3-p194 :003 > (s ||= '') += 'TEST'
SyntaxError: (irb):3: syntax error, unexpected tOP_ASGN, expecting $end
(s ||= '') += 'TEST'
^
from /usr/local/rvm/rubies/ruby-1.9.3-p194/bin/irb:16:in `<main>'
What is it here that differentiates an Array from other types when this syntax form is used?
In Ruby, like in most other languages as well, abbreviated assignments are simply syntactic sugar for the expanded form, i.e.
is syntactic sugar for
So,
is syntactic sugar for
which is simply illegal.
This has absolutely nothing to do with arrays, as you can see here: