From: Robert Klemme Date: 2004-11-06T01:23:42+09:00 Subject: Re: value provided for argument with default value - how to check inside method? "Jamis Buck" schrieb im Newsbeitrag news:418B9D5A.4090704@email.byu.edu... > itsme213 wrote: > > "Robert Klemme" wrote > > > >>I'm unsure what you're at. Normally the idea of having a default value is > >>that you don't have to worry about where it came from: > >> > >>def foo(x=10) > >> puts x > >>end > >> > >>Care to unveil a bit more detail why you would need that piece of > >>information? > > > > > > In this case, I want to use foo() and foo(x) as getter and setter > > respectively i.e. some form of overloading. For getters and setters there's a convention in Ruby already. IMHO in this case it's better to stick with foo/foo= instead of creating a new convention. There are some solutions for the general case of overloading, see here for example: http://www.rubygarden.org/ruby?MethodOverloading > You can always do something like the following. Create a constant and > initialize it to a unique object instance. Then, use that instance as > the default value to your method: > > VALUE_NOT_SPECIFIED = Object.new > def foo( x = VALUE_NOT_SPECIFIED ) > case x > when VALUE_NOT_SPECIFIED > @x > else > @x = x > end > end > > Of course, someone could still explicitly pass the argument > VALUE_NOT_SPECIFIED to the method, but then they would obviously be > trying pretty hard to do what they aren't supposed to do... I'm sure we could find a way to make VALUE_NOT_SPECIFIED private. One can also do this: def foo(*a) @foo = a[0] unless a.empty? @foo end But as I said, my main concern is that this introduces a different pattern for state access while Ruby has such a pattern already. Kind regards robert