From: Hugh Sasse Staff Elec Eng Date: 2001-06-28T20:23:11+09:00 Subject: [ruby-talk:17001] Re: Method overloading (option) Was: Re: On Thu, 28 Jun 2001, Yukihiro Matsumoto wrote: > Hi, > > In message "[ruby-talk:16972] Re: Method overloading (option) Was: Re:" > on 01/06/28, Hugh Sasse Staff Elec Eng writes: > > |> If you give an object of wrong protocol, you'll get NameError (well, > | > |I'm not sure what you mean here. (That could be because I'm implementing > |a 'protocol' on top of UDP at the moment, so I'm see the word differently > |from you! :-)) Can you give an example of how a NameError can come from > |passing the wrong object to a user defined method, without using type > |dispatch, please? This may help me see your Ruby Way. > > 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? I have a vague notion that it might be possible to have a scope based obj.methods_called() method, which would return a list of symbols telling which methods were used in this scope. return [] unless obj.methods_called.all? {|m| obj.respond_to?(m)} or whatever. Is this half-baked idea worth any further consideration? > > matz. > Thank you Hugh