2013-10-17 76 views
4

我看到一个方法定义和使用这样的:单数组参数与多个参数

def mention(status, *names) 
    ... 
end 
mention('Your courses rocked!', 'eallam', 'greggpollack', 'jasonvanlue') 

为什么不直接使用数组作为第二个参数,而不是参数组合成用图示的阵列?

def mention(status, names) 
    ... 
end 
mention('Your courses rocked!', ['eallam', 'greggpollack', 'jasonvanlue']) 

这也将允许更多的论据在最后。

def mention(status, names, third_argument, fourth_argument) 
    ... 
end 
mention('Your courses rocked!', ['eallam', 'greggpollack', 'jasonvanlue'], Time.now, current_user) 
+4

自从Ruby 1.9版本以来,splat参数不一定是最后一个。例如,你可以有'def提及(status,* names,third_argument,fourth_argument)'。作为Ruby的新手,也许是编程,你可能不熟悉术语'code smell',正如@Adam在他的回答中所使用的那样。这始终是一个发情期。人们从来不会听到,“男孩,你的代码味道很棒!” –

回答

2

由于卡里Swoveland和VGOFF提到,像定义

def foo arg1, *args, arg2 
    ... 
end 

是可能的,所以你的最后一点不成立。


这取决于用例。如果该方法采用自然作为数组给出的参数,那么用户传递数组将更容易。例如,假设一个方法以backtrace_locations(数组)为参数。那么这将是更好的有:

def foo arg1, backtrace_locations, arg2 
    ... 
end 
foo("foo", $!.backtrace_locations, "bar") 

而不是:

def foo arg1, *backtrace_locations, arg2 
    ... 
end 
foo("foo", *$!.backtrace_locations, "bar") 

在其他情况下,它是一个类型的参数的灵活号码,然后肖恩Mackesey还指出用户,用户可能会忘记的元件周围的[]只有一个的时候,所以最好做到:

def foo arg1, *args, arg2 
    ... 
end 
foo("foo", "e1", "bar") 
foo("foo", "e1", "e2", "e3", "bar") 

而不是:

def foo arg1, args, arg2 
    ... 
end 
foo("foo", ["e1"], "bar") 
foo("foo", ["e1", "e2", "e3"], "bar") 
foo("foo", "e1", "bar") # => An error likely to happen 
2

图示更加灵活。只需键入参数比放入数组更容易。

+0

你的意思是“输入参数的元素”? – sawa

+0

是的,我的意思是说它比'['a','b','c']'''a','b','c'更容易和更容易输入'''' –

1

这既是关于干净的代码和灵活性。 Splat为您提供了灵活性,同时显式声明每个输入将您的方法绑定得更接近这些输入对象。如果代码稍后改变怎么办?如果你不得不添加更多的字段呢?你知道你会叫他们吗?如果你不得不在别的地方使用这种方法来输入变量呢? Splat增加了很多灵活性,并保持方法声明简洁

列出太多的参数也是一种代码异味。

检查了这一点:How many parameters are too many?

在这里:http://www.codinghorror.com/blog/2006/05/code-smells.html

Long Parameter List: 
The more parameters a method has, the more complex it is. 
Limit the number of parameters you need in a given method, 
or use an object to combine the parameters. 
3

的图示自然的感觉,因为这种方法可以合理地应用到单个或多个名称。它很烦人,而且容易出错,需要在数组大括号中放入单个参数,如mention('your courses rocked!', ['eallam'])。即使一种方法仅适用于Array,该图示也经常保存击键。

而且,没有任何原因,你不能把你的其他参数与*names

def mention(status, arg2, arg3, *names) 
def mention(status, *names, arg2, arg3) 
+1

'在现代Ruby中。 – vgoff