From: Rich Kilmer Date: 2001-11-30T02:55:42+09:00 Subject: [ruby-talk:26942] Re: overload possible? Very Cool! I actually thought about this last night before sleep as well...but I was thinking of adding a "types" method to Array: class Array def types collect {|a| a.type} end end # Then it looks like: if __FILE__ == $0 class Fred def hello(*args) case args.types when [Fixnum, String, Float] i, s, f = args puts "(Fixnum, String, Float) -> [ #{i}, \"#{s}\", #{f} ]" "1" when [String, Fixnum] s, i = args puts "(String, Fixnum) -> [ \"#{s}\", #{i} ]" return "2" else raise TypeError, "Invalid Signature: #{args.types.join(', ')}" end end end f = Fred.new f1 = f.hello(123, "hello", 123.456) f2 = f.hello("hello", 123) f3 = (f.hello("abc", "def") rescue $!) puts "f1 = #{f1.inspect} f2 = #{f2.inspect} f3 = #{f3.inspect}" end I like yours because its explicit (you have a Signature class) but you need a new class (although you also get the "invalid" method which is nice :). Of course, my way you are changing an existing class which may not be great. Unless Matz wants to add the "types" method to Array...since Array is being used in method signature structures, this may conform to his POLS ;-) Either way...this is great and I am going to use it in my code! -Rich > -----Original Message----- > From: nobu.nokada@softhome.net [mailto:nobu.nokada@softhome.net] > Sent: Thursday, November 29, 2001 11:35 AM > To: ruby-talk ML > Subject: [ruby-talk:26930] Re: overload possible? > > > At Thu, 29 Nov 2001 14:05:00 +0900, > Rich Kilmer wrote: > > excellent idea...how about this refactoring... > > I thought up another trick. > > class Signature < Array > def invalid > TypeError.new("Invalid Signature: #{collect {|a| a.type}.join(', ')}") > end > > def ===(args) > length == args.length or return false > each_with_index {|t, i| t === args[i] or return false} > true > end > end > > if __FILE__ == $0 > class Fred > def hello(*args) > case args = Signature[*args] > when Signature[Fixnum, String, Float] > i, s, f = args > puts "(Fixnum, String, Float) -> [ #{i}, \"#{s}\", #{f} ]" > "1" > when Signature[String, Fixnum] > s, i = args > puts "(String, Fixnum) -> [ \"#{s}\", #{i} ]" > return "2" > else > raise args.invalid > end > end > end > > f = Fred.new > f1 = f.hello(123, "hello", 123.456) > f2 = f.hello("hello", 123) > f3 = (f.hello("abc", "def") rescue $!) > > puts "f1 = #{f1.inspect} f2 = #{f2.inspect} f3 = #{f3.inspect}" > end > > Nobu Nakada