From: Gennady Date: 2004-01-24T08:56:18+09:00 Subject: Re: detecting default parameters Daniel Doel wrote: > Ian Macdonald wrote: > >>Hello, >> >>Does anyone know of a way to detect whether default parameters are >>beingused in a method? I'm looking for something like the pseudo- >>method'default?' in the following example: >> >>def my_method(foo='bar') >> if foo.default? >> puts "warning: default value #{foo} being used for 'foo'" >> end >>end >> >>I suspect Ruby no longer holds any state at this point to reflect the >>fact that the caller did not supply a parameter, but I'm hoping >>there'ssome way to do it. > > > Try this: > > #!/usr/bin/ruby > > class Object > def default? > false > end > end > > def default(obj) > defparam = obj.clone > > class << defparam > def default? > true > end > end > > defparam > end > > def foo(bar=(default 'foo')) > if bar.default? > puts "default" > else > puts "custom" > end > > puts bar > end > > foo 'baz' > foo > > This might be as close as you'll get. It doesn't work for everything, though, since you can't clone everything, and I don't want to redefine #default? on things you can't clone (like Fixnums) since that'd make things wrong. > > - Dan > > Interesting. It seems like you could use SimpleDelegator here: require 'delegate' def default(obj) defparam = SimpleDelegator.new(obj) class << defparam def default? true end end defparam end