Leem.fin Leem.fin - 2 months ago 11
Ruby Question

Unknown argument when call a function in another function

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?

Answer

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')
Comments