From: David Alan Black Date: 2001-06-28T22:08:30+09:00 Subject: [ruby-talk:17005] Re: Method overloading (option) Was: Re: On Thu, 28 Jun 2001, Hugh Sasse Staff Elec Eng wrote: > On Thu, 28 Jun 2001, Yukihiro Matsumoto wrote: [...] > > def split(obj) > > a = [] > > len = obj.size > > for i in 0...len > > a.push obj[i] > > end > > a > > end > > > > p split("abc") # [?a, ?b, ?c] > > p split([1,2,3]) # [1, 2, 3] > > p split(:foo) # -:3:in `split': undefined method `size' for :foo:Symbol (NameError) > > > > the "split" takes any object that responds to "size" and "[]". "size" > > and "[]" are protocol this case. > > OK, thank you. That is clear. Now, one can add (I'm writing this > like a patch) : > > def split(obj) > a = [] > + return a unless obj.respond_to?(:size) > + return a unless obj.respond_to?(:[]) > len = obj.size > for i in 0...len > > and so on for the other methods one might use, but how does that get around > having to refer to methods in more than one place, that I asked about? Maybe just handle the exception: def split(obj) a = [] begin len = obj.size for i in 0...len a.push obj[i] end rescue NameError end a end I'm not sure whether that might be casting too wide a net, though -- i.e., whether there might be a case where a NameError might come about for some unrelated reason and you'd want it handled elsewhere. Still, I think that for this kind of many-to-one error-to-outcome ratio, exceptions might be a good way to go. David -- David Alan Black home: dblack@candle.superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav