0

In my module, I defined two functions have the same name but different number of arguments.

module MyMod
 def self.doTask(name:, age:)
    doTask(name: "John", age: 30, career: "Teacher")
 end

 def self.doTask(name:, age:, career:)
   puts "name:#{name}, age:#{age}, career:#{career}"
 end
end

As you see above, in doTask, I just call doTask.

In another Ruby file, I call the doTask by:

MyMod.doTask(name:"Kate", age: 28)

But I get runtime error:

unknown keyword: career (ArgumentError)

Why?

4
  • When you're calling the method you're actually passing it a single hash as an argument, just so you know. Commented Sep 13, 2016 at 7:42
  • 1
    @sagarpandya82 no. This is keyword arguments. See robots.thoughtbot.com/ruby-2-keyword-arguments Commented Sep 13, 2016 at 7:44
  • @pascalbetz ah, thanks. Commented Sep 13, 2016 at 7:48
  • "I defined two functions have the same name" – No, you didn't. First off, you didn't define functions, you defined methods, that's an extremely important distinction. Ruby doesn't have functions. Second, you defined a method, then you defined it again, overwriting the previous definition. Commented Sep 13, 2016 at 10:21

2 Answers 2

4

Ruby does not have method overloading. You can not have multiple methods with the same name.

One solution would be to use a the three argument version of the method and add a default value for the :career argument.

module MyMod
  def self.doTask(name:, age:, career: "Teacher")
    puts "name:#{name}, age:#{age}, career:#{career}"
  end
end
MyMod.doTask(name:"Kate", age: 28)
MyMod.doTask(name:"Kate", age: 28, career: 'Teacher')
MyMod.doTask(name:"Kate", age: 28, career: 'Mechanic')
Sign up to request clarification or add additional context in comments.

2 Comments

Could you please provide some code just to be clear? Thanks
nice! exactly what I want. Thanks.
2

Ruby doesn't support method overloading (2 methods with the same name and different parameters) so your second method definition with the career parameter is replacing the first method definition.

You can provide a default value for the optional parameter like this:

def self.doTask(name:, age:, career: 'Employee')
 puts "name:#{name}, age:#{age}, career:#{career}"
end

and then career will have the value "Employee" if not specified.

or default to nil and include some logic in the method body to handle

def self.doTask(name:, age:, career: nil)
  unless career.nil?
    # doTask with career
  else
    # doTask without career
  end
end

If you're coming to Ruby from another language like Java or C# then there's some great insight into why the equivalent behaviour doesn't exist in Ruby in this answer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.