ruby - Unknown argument when call a function in another function -
in module, defined 2 functions have same name 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 see above, in dotask
, call dotask
.
in ruby file, call dotask
by:
mymod.dotask(name:"kate", age: 28)
but runtime error:
unknown keyword: career (argumenterror)
why?
ruby not have method overloading. can not have multiple methods same name.
one solution use 3 argument version of method , add default value :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
Post a Comment