Named arguments in Ruby

djberg96 on 2002-05-06T18:54:03

One of the things I really like about Perl, especially when doing Tk programming, is named arguments.

Until recently, I didn't think this was possible in Ruby short of using an anonymous hash and parsing the hash in the 'initialize' method. However, Guy Decoux recently provided this idiom: module SomeMod def initialize(attributes) attributes.each do |k, v| type.send(:attr_accessor, k) send("#{k}=", v) end end end

sm = SomeMod.new(name=>'Dan',rank=>'SrA') puts sm.rank #=> 'SrA' sm.rank = 'General' puts sm.rank #=> 'General'

Not only does this let you do named arguments with Ruby, it automatically provides get/set ability. Will Perl 6 be able to do this, hmmm?

The only downside is that you'll have to manually parse out any bogus attributes a programmer might try and create.


Type checking

Matts on 2002-05-07T15:53:36

Still no parameter checking though. It's a shame, as this is one area where Python still kicks both Perl and Ruby's ass.

Re:Type checking

djberg96 on 2002-05-07T17:39:02

I'll probably get slapped for this but, "so what?". I have never, ever missed this "feature" in either Perl or Ruby. I think Dave Thomas pretty well summed up my feelings about it here

I'm genuinely curious as to what advantage you think this would bring to Ruby, or whether or not you think this is a real selling point for Python.

Re:Type checking

Matts on 2002-05-07T21:41:37

Sorry, I realised later the subject of my post wasn't what I meant.

I meant simply that this sort of thing (named params) should be built in, with checking done on the actual names passed in, performed at the parser level. I don't mean to imply checking of the type of a variable.

This covers 90% of the times you need to pass named parameters (the other 10% being where you might not know the names you need to pass ahead of time - in which case you construct your API so you can pass a hash instead), and would certainly help catch a large number of hash-related typos.

Re:Type checking

djberg96 on 2002-05-08T12:44:20

Ah, I see. Myself and others have suggested that as a feature for Ruby 2.0. Whether or not it's adopted remains to be seen. Given that Ruby 2.0 is vaporware at the moment, it's not much of an issue.

Will Perl 6 handle this any differently?