From: Josh Cheek Date: 2011-01-28T06:01:37+09:00 Subject: Re: why is overloading invalid in ruby. --0016364ee65c701b70049ada4048 Content-Type: text/plain; charset=ISO-8859-1 On Thu, Jan 27, 2011 at 1: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/. > > Ruby methods don't really have signatures, so overloading would be quite difficult. Disregarding your first sum, which adds 2, for some unknown reason, I would write the method like this: def sum(*numbers) sum = 0 numbers.each { |number| sum += number } sum end Okay, I would probably actually write it like this, which is the same thing, but less accessible to people who haven't encountered inject or reduce before. def sum(*numbers) numbers.inject { |sum,number| sum + number } end It could then be called with any number of arguments and types sum 1 # => 1 sum 1 , 2 # => 3 sum 5 , 9 , 10 # => 24 sum 8 , 8 , 16 , 32 # => 64 sum 1.5 , 2.3 # => 3.8 In fact, it is flexible enough to take non-numeric types, though you probably wouldn't ever use such a thing. sum 'a' , 'b' # => "ab" sum [1,2] , [3,4] # => [1, 2, 3, 4] --0016364ee65c701b70049ada4048--