From: Gavin Sinclair Date: 2002-11-14T09:43:59+09:00 Subject: Re: Keyword arguments? From: "ahoward" > On Tue, 12 Nov 2002, Vis Mike wrote: > > [snip] > > Keyword arguments help with ambiguity. > [snip] > > this is close > > class Person > def initialize args > @name = args[:name] > @age = args[:age] > end > end > > me = Person.new :name => 'ara', :age => 30 > 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