From: James Edward Gray II Date: 2006-12-07T00:47:16+09:00 Subject: Re: Default values for method arguments On Dec 6, 2006, at 9:30 AM, paul wrote: > The Simulated Keyword Arguments you talk about are a little > abstract to > me, but I think I get the idea. My fault, I did not describe them very well. Here are the critical bits of information: If a method call ends with some arguments that look like a Hash definition (using the fat arrows =>), Ruby collects those and passes a single Hash to the method in their place. You can then work with the Hash normally. > 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 Another way to set defaults: >> def test(args) >> args = { "a" => "default a", ?> "b" => "default b", ?> "c" => "default c" }.merge(args) >> puts args.values_at("a", "b", "c") >> end => nil >> test "a" => "some a", "c" => "some c" some a default b some c => nil > An additional question: do you know a link where I can find more on > those Simulated Keyword Arguments? See Collecting Hash Arguments at the bottom of: http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_methods.html > 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...) :) Those are just Symbol objects. Don't lose too much sleep over them yet, as you can see from the new example Strings work fine too. James Edward Gray II