函数重载是否在ruby中工作?

时间:2013-08-25 22:10:13

标签: ruby overloading

你能否像在C中那样在ruby中定义同一函数的多个版本?

E.g。

def meth(name, string, thing)

def meth(array_of_things)

ruby​​会根据传入的变量调用正确的方法吗?

如果不能,我怎么能做到这一点。

2 个答案:

答案 0 :(得分:4)

不,Ruby不支持方法重载。如果您定义两次具有相同名称的方法,则第二个定义将替换第一个。


为了达到同样的效果,你需要获取可变数量的参数,然后检查运行时的数量。

虽然可能有点矫枉过正。通常最好的想法只是给你的两种方法命名不同。

答案 1 :(得分:3)

这在Ruby中已经完成了。有几种方法可以做到。

通过使用duck typing,你可以这样做:

def meth arg1, arg2 = nil, arg3 = nil
  if arg1.respond_to?(:some_method) then ...
  else ...
  end
end

根据参数的数量,你可以这样做:

def meth *args
  case args.length
  when 3 then ...
  when 1 then ...
  end
end

通过第一个元素的类,您可以:

def meth *args
  case args.first
  when String then ...
  when Symbol then ...
  end
end

使用可选参数,您可以:

def meth arg1, arg2 = nil, arg3 = nil
  if arg2 then ...
  else ...
  end
end

我最喜欢这种做法的应用是当我有一对setter和getter方法时。当没有给出参数时,该方法用作吸气剂;当给出一个参数时,它就像一个设定者。例如,如果obj上定义了getter / setter方法foo,我可以以任何一种方式使用它:

obj.foo               # as a getter
obj.foo(some_value)   # as a setter

我是从jQuery API学到的。