From: Stefano Crocco Date: 2011-01-28T04:59:22+09:00 Subject: Re: why is overloading invalid in ruby. On Friday 28 January 2011 04:22:47 Ted Flethuseo wrote: > I don't understand why when I try to overload I get an error. Can I > overload somehow? > > #!/usr/bin/env ruby > > class Summer > def sum(x) > return x + 2 > end > > def sum(x,y) > return x + y > end > > def sum(x,y,z) > return x + y + z > end > end > > s = Summer.new > puts s.sum(3) > > ERROR: > ArgumentError: wrong number of arguments (1 for 3) > > method sum in summer.rb at line 18 > at top level in summer.rb at line 18 > > > Ted Ruby doesn't support method overloading. What your code does is giving three definition of the sum method, with each definition overwriting the previous one. This means that the first two definitions have no effect, since they're overwritten by the third. At the end of your code, the sum method is defined to take three arguments, so you obviously get an error when you try to call it with only one argument. You can achieve the same result giving some of the arguments default values: class Summer def sum x, y = 2, z = 0 x + y + z end end Now the sum method can be called with one, with two or with three arguments. In the first case, y will be 2 and z will be three, so the result will be computed as x + 2 + 0 which is what you wanted. If it's called with two arguments, x and y will be given the values passed as argument and z will be 0. Another approach is to give sum a variable number of arguments, like this: def sum x, *args args << 2 if args.empty? res = x args.each{|i| res += i} res end The * in front of args in the method definition tells ruby that args is special: it stands in place of any number of arguments, from 0 upwards. When the method is called, the first argument is assigned to x. Any other argument (if any) is put in an array which is assigned to the variable args. In particular, if sum is called with only one argument, args will be empty, so we insert the value 2 in it (by the way, you could use Array#inject here, which is much more elegant than what I wrote). I hope this helps Stefano