2

I am trying to do the following:

class SUM
  def make_sum (number)
    return number+number
  end 

  def make_sum (number_a, number_b)
    return number_a+number_b
  end 
end

operation = SUM.new
operation.make_sum(5)    # returns 10
operation.make_sum(2, 3) # returns 5

make_sum method of one input is re-defined by the one with two inputs.

mareiou
  • 404
  • 2
  • 11
  • 2
    I agree with Jonny. While not strictly a duplicate in terms of how the question is stated, it touches the nature of the problem: "number of arguments", "types of arguments" etc is actually usually called 'overloading' rather than 'polymorphism'. Polymorphism is a bit different thing, and multiple-dispatch is also a different thing than 'numerbs of inputs'. The 'why doesn't ruby(..)' question shows that overloading is not supported and why and this sums up this question too. – quetzalcoatl Jun 06 '16 at 17:08
  • 1
    However, as Keith and marcus show in their answers, even if the 'overloading' is not possible, you can emulate it with `*args` trick - take arguments as array, inspect lenght of that array, and then do something different depending on that length. But that's neither polymorphism, nor overloading. That's just manual coding with no object-oriented name (since it has nothing to do with OO :) ). A common name for that is just `splat args` or `splat operator`. [See here for some examples](http://jacopretorius.net/2012/01/splat-operator-in-ruby.html) – quetzalcoatl Jun 06 '16 at 17:12
  • No, you can't define two methods with the same name but different arguments in ruby. The last one 'won', the first method definition isn't there at all anymore. – jrochkind Jun 06 '16 at 21:02

2 Answers2

2

If the addition is what you're after, you can do it more simply as:

def add(*numbers)
  numbers.inject(&:+)
end

add(1) # => 1
add(1, 3, 5) # => 9

If you're looking for a more general solution to the problem of how to provide behavior dependent on the number of arguments, then you use *args in the signature and then branch based on args.size:

def foo(*args)
   case args.size
     when 1
        # do something
     when 2
        # do something else
     when (3..5)
        # do another thing
   end
 end
Keith Bennett
  • 4,722
  • 1
  • 25
  • 35
0

I had the same reaction to this as @keith-bennett. But I was unaware that it was as simple as his answer. Here was my solution:

class Foo
  def self.add(*args)
      r = 0
      if args.length > 1
          args.each { |a| r += a.to_i }
      else
          r += (args[0].to_i + args[0].to_i)
      end
      return r
  end
end

f = Foo
puts f.add(1, 2)
# => 3
puts f.add(1)
# => 2
marcusshep
  • 1,916
  • 2
  • 18
  • 31