2013-10-17 74 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