Although I have already written Ruby, I am always looking for ways to improve my style.
I'm used to a particularly short, concise method of instantiating + adding to an array:
ruby-1.9.3-p194 :001 > (a ||= []) << 1 => [1]
This particular syntax seems only valid when used in conjunction with arrays, since 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 the lines, although I pretty much expected that this would not work given the previous 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 distinguishes an array from other types here when this syntax form is used?
source share