Hi --

On Sun, 24 Jun 2007, darren kirby wrote:

> I have a method here that takes two arguments. Both are optional, with
> appropriate default values. The first is a string which represents a filename
> to write data to. The second is an integer which represents which data from a
> choice of 1 or more should be written to the file.
>
> So I have:
>
>> def write_picture(outfile = nil, n = 1)
>
> When I call as:
>
>> write_picture()
>
> it does the right thing and uses both defaults.
>
> When I call as:
>
>> write_picture("somefile")
>
> it does the right thing and writes the default data to "somefile"
>
> When I call:
>
>> write_picture("front cover", 1)
>> write_picture("back cover", 2)
>
> it does the right thing. However, when I do:
>
>> write_picture(n=1)
>
> I am sure you can guess what happens. I get a picture written to a file
> with "1" as a filename. This seems like non-intuitive behavior. With no
> support for named args shouldn't it error here?

You're performing a local variable assignment.  Try this and you'll
see:

   write_picture(n=1)
   puts n

:-)

> Now: I gather I can do:
>
>> def write_picture(*args)
>
> and perhaps do a type check on each argument, as there must be one each String
> and Integer, and sort them out appropriately. However, this relies too
> heavily, for my comfort, on the users passing sane values to the method.
>
> Is there a clean way to accomplish my goal? Are there plans to give named
> arguments to Ruby in the future?

The usual idiom for this is to use a hash:

   write_picture(:outfile => "file.out", :n => 1)

I've lost track of where things stand with named arguments in future
Rubies but the hash technique is generally quite adequate.


David

-- 
* Books:
   RAILS ROUTING (new! http://www.awprofessional.com/title/0321509242)
   RUBY FOR RAILS (http://www.manning.com/black)
* Ruby/Rails training
     & consulting:  Ruby Power and Light, LLC (http://www.rubypal.com)