From: Ken Bloom Date: 2006-12-07T00:55:06+09:00 Subject: Re: Default values for method arguments On Wed, 06 Dec 2006 07:27:00 -0800, paul wrote: >> You just need to switch strategies. Use Ruby's simulated keyword >> arguments for something like this: >> >> >> def test(args) >> >> puts args.values_at(:a, :b, :c) >> >> end >> => nil >> >> test :a => 1, :c => 2 >> 1 >> nil >> 2 >> => nil > Hi James, > > The Simulated Keyword Arguments you talk about are a little abstract to > me, but I think I get the idea. I suppose in the example above I would > have to add a couple of lines to define the default values... > This way, the general idea is the same as the following? > > irb(main):001:0> def test(args) > irb(main):002:1> args['a'] = 'defaultA' unless args.has_key?('a') > irb(main):003:1> args['b'] = 'defaultB' unless args.has_key?('b') > irb(main):004:1> args['c'] = 'defaultC' unless args.has_key?('c') > irb(main):005:1> puts args.indexes('a', 'b', 'c') > irb(main):006:1> end > => nil > irb(main):007:0> test({'a' => 'someA', 'c' => 'someC'}) > (irb):5: warning: Hash#indexes is deprecated; use Hash#values_at > someA > defaultB > someC > => nil Try this-- it's more concise, and you probably won't feel the need for more syntactic magic after that. def test(args) args[:a] ||= 'defaultA' args[:b] ||= 'defaultB' args[:c] ||= 'defaultC' puts args.indexes(:a, :b, :c) end > > An additional question: do you know a link where I can find more on > those Simulated Keyword Arguments? I did some googling, but it turned > up with nothing on: > ruby "Simulated Keyword Arguments" > > Those colons you use before the variable-names are a little like magic > to me. (though I checked, without those colons, you're example above > wouldn't have worked...) :) The colons make them into symbol objects. > Cheers, > Paul -- Ken Bloom. PhD candidate. Linguistic Cognition Laboratory. Department of Computer Science. Illinois Institute of Technology. http://www.iit.edu/~kbloom1/