1

I have this piece of code in Ruby.

class Superheros
class<<self

    def foo1(param1)
        print "foo1 got executed\n"
    end

    def foo1
        print "foo1 without param got executed\n"
    end
    def foo3(param1,param2)
        print "foo3 got executed\n"
    end
end
end

print Superheros.foo3(2,3) 
print Superheros.foo1
print Superheros.foo1 
print Superheros.foo1(5)

I get the error in Superheros.foo1(5) . But i already have the function foo1(param1) to match it with, but it gives me an error `foo1': wrong number of arguments (1 for 0) (ArgumentError)

Why is that? PS: I found out if i remove the function name without the parameter, the Superheros.foo1(5) works just fine.

SeasonalShot
  • 2,357
  • 3
  • 31
  • 49

2 Answers2

3

Ruby doesn't support method overloading. In your code, your second definition of foo1 replaced the first. That's why you get an error when you try to pass arguments, the method that accepted arguments is gone.

There is a question on SO about this topic here, with some good explanations.

Community
  • 1
  • 1
victorkt
  • 13,992
  • 9
  • 52
  • 51
1

Maybe you could use variable arguments:

def foo1(*args)
  case args.length
    when 1
      puts "Function A"
    when 2
      puts "Function B"
    else
      puts "Called with #{args.length} arguments"
  end
end