Feature #7132

Updated by Nobuyoshi Nakada about 3 years ago

Hi everyone. I am using Ruby for >1 year and I would like to share with you my dreams regarding the named method arguments planned for 2.0. Let us imagine a class Thief with 3 properties (name, hit_points and dexterity), which has constructor #new_thief:

new_thief name: "John Fingers", hit_points: 14, dexterity: 15

I dream about this constructor accepting alternative syntax:

new_thief "John Fingers", hit_points: 14, dexterity: 15

and accepting synonyms (aliases) :hp for :hit_points and :dex for dexterity:

new_thief "John Fingers", hp: 14, dex: 15

To explain my motivation, I am creating a DSL in biology. I am facing the challenge of explaining to my colleagues why is it better than their current Java app. Biologists love synonyms, and I'd like the users calling constructors for biological objects to have freedom to use the synonym they like. Of course, I can already achieve it in 1.9.3:

def new_thief *args
oo = args.extract_options!
raise ArgumentError if args[0] and oo[:name] and args[0] != oo[:name]
name = args[0] || oo[:name] || "John Doe"
raise ArgumentError if oo[:hp] and oo[:hit_points] and oo[:hp] != oo[:hit_points]
hp = oo[:hp] || oo[:hit_points] || 9
raise ArgumentError if oo[:dex] and oo[:dexterity] and oo[:dex] != oo[:dexterity]
dex = oo[:dex] || oo[:dexterity] || 11
Thief.new( name: name, hit_points: hp, dexterity: dex )

But I find myself doing this over and over, and even if I write a library to make it easier, it's still too cumbersome.

Proposal no. 1: I propose that alternation between named / ordered arguments and aliases (synonyms) for named method arguments be catered for already by core syntax.

Proposal no. 2: I propose that the syntax for this be as follows:

def new_thief( name=**:name="John Doe", hp: **:hit_points=14, dex: **:dexterity=15 )
Thief.new name: name, hit_points: hp, strength: str, dexterity: dex

where expressions **:arg_name would refer to the named argument :arg_name.

Please judge the two proposals independently. I really dream about having the alternation between named / ordered arguments and aliases for named arguments in Ruby 2.0. But I feel less sure that the syntax **:arg_name that I am proposing is the best possible syntax for this. Mind me, I don't think it is bad, I am just not sure it is *best*.

PS: Please forgive me suggesting such a complicated feature, while being unable to write a single line in C.