Stories
Slash Boxes
Comments
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

djberg96 (2603)

djberg96
  (email not shown publicly)

Journal of djberg96 (2603)

Monday May 06, 2002
01:54 PM

Named arguments in Ruby

[ #4698 ]
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.

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
 Full
 Abbreviated
 Hidden
More | Login | Reply
Loading... please wait.
  • Still no parameter checking though. It's a shame, as this is one area where Python still kicks both Perl and Ruby's ass.
    • 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 [google.com]

      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.

      • 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
        • 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?