From: "Peña, Botp" Date: 2002-11-14T11:41:45+09:00 Subject: Re: Keyword arguments? cool. I like Gavin's code below. Is there a Ruby Tips/SampleCodes page? Gavin's code is worth pasting :-) ..probably under Tips->Argument Processing->Gavin->Sample code... Kind regards, -botp > Gavin Sinclair [mailto:gsinclair@soyabean.com.au] expounded: > ... > Amidst all the discussion of various ways of achieving > keyword arguments or similar, one really nice feature has > been overlooked: easy default arguments. Here is a > representation of code I've written recently. > > class Recorder > def initialize(init_params={}) > init = process_params(init_params) > @database = init[:DATABASE] > @user = init[:USER] > @password = init[:PASSWORD] > end > > def Recorder.init_defaults > { > :DATABASE = "...", > :USER = "...", > :PASSWORD = "...", > } > end > > def process_params(hash) > defaults = init_defaults() > # Guard user against invalid keys > hash.keys.each do |key| > raise "Key not supported: #{key}" unless defaults.has? key > end > defaults.update(hash) > end > end > > > Now, > Recorder.new and > Recorder.new(:USER => "smith", :PASSWORD => "apple") > will use the appropriate defaults, and > Recorder.new(:LOG_FILE => "x.log") > will fail with a meaningful error message. > > Further, if anyone wants to find out the defaults, they only > have to ask: > Recorder.init_defaults > > I've been very happy with this, and see no need for Ruby to > adopt explicit keyword arguments. > > Gavin > >