ruby picture

RCR 181: Allow parens around a single target variable in multiple val

Submitted by coreywangler (Tue Jan 06 03:01:16 UTC 2004)

Abstract

Allow parenthesis around a single target variable, meaning assign the first element of the corresponding sub-array. This is a logical extension of the currently allowable syntax.

Problem

Current syntax for grouping target values in multiple value assignment is incomplete.

Proposal

Allow parens around a single target value, meaning assign the first element of the corresponding sub-array.

New behaviour...

  (a),b,c = [1,2],[3,4],[5,6]
  ==> a=1, b=[3,4], c=[5,6]
  ((a),(b,c),d) = [[1,2,3],[4,5,6],[7,8,9]]
  ==> a=1, b=4, c=5, d=[7,8,9]
  ((a),(b,c),d) = [1,2,3,4,5]
  ==> a=1, b=2, c=nil, d=3

...just as (b,c) assigns the first and second elements of the corresponding sub-array to b and c respectively and ignores any remaining elements of that sub-array, (a) should similarly assign the first element of the corresponding sub-array to the target value a and ignore the other elements of that sub-array.

ASIDE: Note that the following multi-value assignments all mean the same thing, as (in my thinking) omitting the outer parens (on LHS) or brackets [on RHS] is allowed in a similar way to that which parens can be omitted from method calls (thus conforming to the "principle of least surprise")...

  def foo
    return [1,2],[3,4],[5,6]   #returns an Array [[1,2],[3,4],[5,6]]
  end
   (a),b,c  =  foo
  ((a),b,c) =  foo
  ((a),b,c) = [[1,2],[3,4],[5,6]]
  ((a),b,c) =  [1,2],[3,4],[5,6]
   (a),b,c  = [[1,2],[3,4],[5,6]]
   (a),b,c  =  [1,2],[3,4],[5,6]
  #all of these give ==> a=1, b=[3,4], c=[5,6]

So Matz, I recon the current behaviour is correct ("semantics on multiple values" in Ruby 2)...

  x = [1,2,3]
  a, b, c = x
  ==> a=1, b=2, c=3

...as the programmer can think of it as allowing outer parens and brackets to be omitted. i.e.

  x = 1,2,3     same as saying    x = [1,2,3]
...and...
  a,b,c = x     same as saying    (a,b,c) = x

Analysis

This proposal is a logical extension of existing syntax, and makes multiple value assignment a more powerful language construct.

Will not break current code, as this is new syntax.

Implementation

Language modification is required.
ruby picture
Comments Current voting
Strongly opposed 0
Opposed 0
Neutral 0
In favor 0
Strongly advocate 0
ruby picture

This RCR has been superseded by RCR 182.

ruby picture

Powered by .