Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
函数重载在ruby中有效吗?_Ruby_Overloading - Fatal编程技术网

函数重载在ruby中有效吗?

函数重载在ruby中有效吗?,ruby,overloading,Ruby,Overloading,你能用ruby定义同一函数的多个版本吗?就像在C中一样 例如 及 ruby会根据传入的变量调用正确的方法吗 如果不是的话,我怎么能做到这一点呢。这是用Ruby做的。有几种方法可以做到这一点 通过使用duck键入,您可以执行以下操作: def meth arg1, arg2 = nil, arg3 = nil if arg1.respond_to?(:some_method) then ... else ... end end def meth *args case args.l

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

例如

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


如果不是的话,我怎么能做到这一点呢。

这是用Ruby做的。有几种方法可以做到这一点

通过使用duck键入,您可以执行以下操作:

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
根据参数的数量,您可以执行以下操作:

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
通过第一个元素的类,可以执行以下操作:

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
使用可选参数,可以执行以下操作:

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方法时。当没有给出参数时,该方法充当getter;当一个参数被给出时,它就像一个setter。例如,如果有一个obj上定义了getter/setter方法foo,我可以用以下两种方式使用它:

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

我从jQueryAPI学到了这一点。

不,Ruby不支持方法重载。如果您用相同的名称定义了一个方法两次,那么第二个定义将简单地替换第一个定义

为了达到同样的效果,您需要获取数量可变的参数,然后在运行时检查有多少参数


但这取决于上下文,可能有点过头了。通常,最好的办法是简单地给两个方法取不同的名称。

很有趣,不过我会非常小心地将getter和setter混为一谈。这两种行为是完全不同的查询和命令,我希望它们在一个典型的API中有所区别。为什么你不使用一个链中的Obj.fo=某个值?@ SEPP2K,有一个返回接收器的东西更方便,就像JQuery设置器一样。此外,我还提到了一些自定义设置程序,它们可能不仅仅是为实例变量赋值;你可能会想到C++。