From: Trans Date: 2005-10-23T10:22:01+09:00 Subject: Re: A comparison by example of keyword argument styles Bill Guindon wrote: > It's always seemed strange to me that the two formats differ, seems a > nuisance when you've built up either the attr_accessor list, or your > parameter list, and you have to hand massage one to the other. > > class Format > attr_accessor :font_face, :font_color, :font_size, :bold, :italic > def initialize > parameters :font_face='arial' > keywords :font_color='black', :font_size, :bold=false, :italic=false > ... > end > end > > format = Format.new('verdana') > format = Format.new(font_size: 1, bold: true) > format = Format.new('verdana', italic: true, font_size: 10) > > granted, functon calls and constructors could still get quite lengthy. But you can mitigate that. Also there's no need for this on regular parameters, they can remain pretty much the same, though something like this might be nice default values. Anyway: class Format attr_accessor :font_face, :font_color, :font_size, :bold, :italic def initialize(font_face='arial') key :font_color=>'black' key :font_size key :bold=>false key :italic=>false ... end end or just class Format attr_accessor :font_face, :font_color, :font_size, :bold, :italic def initialize(font_face='arial') keys :font_size, :font_color=>'black', :bold=>false, :italic=>false ... end end Though I am not using the new named parameters for the #keys method itself here. Even so this is kind of nice. It's kind of like the lisp stuff too. And in a way it's like a "keywords block", in fact: class Format attr_accessor :font_face, :font_color, :font_size, :bold, :italic def initialize(font_face='arial') keys :font_size, :font_color=>'black', :bold=>false, :italic=>false puts "keeps the keys out ot the paranthetical" end end The only things is that means key/keys becomes a keyword (no pun intended). At least I think it would. Well, in that case we could take it a bit further and pull a page out of Alex' book -- it might be even nicer to predefine these keys: class Format attr_accessor :font_face, :font_color, :font_size, :bold, :italic initkeys = keys :font_size, :font_color=>'black', :bold=>false, :italic=>false def initialize( font_face='arial', *initkeys ) puts "keeps the keys out ot the paranthetical" end end Then they be reusable. Could extend this to parameters in general too. T.