From: Andrew Wagner Date: 2011-01-28T04:44:30+09:00 Subject: Re: why is overloading invalid in ruby. --000e0cd1e32a5acac7049ad92726 Content-Type: text/plain; charset=UTF-8 On Thu, Jan 27, 2011 at 2:22 PM, 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 > > -- > Posted via http://www.ruby-forum.com/. > > The problem is that when you define a method in a class that already has a method with that name, it replaces it. So your class is left with only one method, the one with 3 arguments. The first 2 get destroyed. The more ruby-esque way to do this is to use optional parameters. Here's one simple solution: def sum(x,y=0,z=0) return x + y + z end --000e0cd1e32a5acac7049ad92726--