ruby picture

RCR 315: allow required arguments after optional arguments

Submitted by eric_mahurin (Sun Sep 11 16:48:43 UTC 2005)


In the method defintion, allow required arguments (not splatted and no default) to appear after optional arguments (defaults given) and/or a splatted argument array (i.e. *args).


When you have a method that you want optional arguments to come before some required arguments:

a [, b [, c ...]], d

you have to do something like this:

 def foo(a,*remaining)
   d = remaining.pop
   b = remaining.empty? ? b_default : remaining.shift
   c = remaining # splatted argument array

A primary example would be for the []= method where the calling syntax is:

object[ arg,... ] = value

The receiving method gets the arguments in the same order as listed above. The variable length list of arguments between the [] comes first and the value is last. Unless the []= method has a fixed number of arguments between the [], the method will have to do something like above to pop off the value from the argument list.


Simply extend the syntax to allow required arguments to appear after the optional ones:

 def foo(a, b, c=c0, d=d0, *e, f, g) ... end

would be equivalent to:

 def foo(a, b, *remaining)
   f,g = remaining.slice!(-2,2)
   c = remaining.empty? ? c0 : remaining.shift
   d = remaining.empty? ? d0 : remaining.shift
   e = remaining

Also consider the cases where the optional arguments (c,d) or the splatted arg array (e) aren't there.

An optional part of this RCR would be to apply this to multi-assign statments. The following:

 a,b,*c,d,e = mrhs

would be equivalent to:

 a,b,*remaining = mrhs
 d,e = remaining.slice!(-2,2)
 c = remaining


no backwards incompatibilities


changes the ruby parser and how arguments are put into the method argument variables
ruby picture
Comments Current voting
I'm more or less in favour of this idea, but this is something that I think may have problems with named arguments -- and I'm not sure that the form for that has been set.

The implementation section needs some love - have you looked at the C code needed to implement this at all?

This would be very useful for #[]= methods.

  def []= (*coords, value)
    # ...

It's much cleaner and intuitive than having to write

  def []= (*args)
    value = args.pop
    coords = args
    # ..

Strongly opposed 1
Opposed 0
Neutral 0
In favor 3
Strongly advocate 2
ruby picture
If you have registered at RCRchive, you may now sign in below. If you have not registered, you may sign up for a username and password. Registering enables you to submit new RCRs, and vote and leave comments on existing RCRs.
Your username:
Your password:

ruby picture

Powered by .