From: Chris Shea Date: 2009-08-20T05:40:07+09:00 Subject: Re: #has_arguments? On Aug 18, 11:37 pm, Intransition wrote: > Messing with optional argument check for the umpteenth time, eg. > >   def meth(a=Exception) >     if a != Exception >        ... >     else >       ... >     end >   end > > Other's might do: > >   def meth(*a) >     if !a.empty? >       a = a.first >        ... >     else >       ... >     end >   end > > Neither of which are very satisfying. So it occurs to me tonight that > we already have #has_block? to see if a block was passed. So how about > a #has_arguments? to query if _any_ arguments have been passed. So > then... > >   def meth(a=default) >     if has_arguments? >        ... >     else >       ... >     end >   end > > Ah... now that would be nice. Here's a little trick I learned (very hacky): def meth(a=(no_argument='default')) if no_argument 'nothing given' else "we got #{a.inspect}" end end Your default argument can't be falsy (but you could use something truey and use your falsy value in its place). Anyway: 036:0> meth "nothing given" 037:0> meth(nil) "we got nil" 038:0> meth('whatever') "we got "whatever"" 039:0> meth "nothing given" I can't vouch for JRuby or Ruby 1.9 or Rubinius or IronRuby for this one (work's a strictly 1.8.6 kind of place). -Chris