On Thu, Jan 27, 2011 at 2:22 PM, Ted Flethuseo <flethuseo / gmail.com> 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