ruby – 单个数组参数与多个参数
发布时间:2020-12-17 03:40:34 所属栏目:百科 来源:网络整理
导读:我看到一个定义和使用的方法如下: def mention(status,*names) ...endmention('Your courses rocked!','eallam','greggpollack','jasonvanlue') 为什么不使用数组作为第二个参数而不是使用splat将参数组合到数组中? def mention(status,names) ...endmenti
我看到一个定义和使用的方法如下:
def mention(status,*names) ... end mention('Your courses rocked!','eallam','greggpollack','jasonvanlue') 为什么不使用数组作为第二个参数而不是使用splat将参数组合到数组中? def mention(status,names) ... end mention('Your courses rocked!',['eallam','jasonvanlue']) 这也可以在最后允许更多的参数. def mention(status,names,third_argument,fourth_argument) ... end mention('Your courses rocked!','jasonvanlue'],Time.now,current_user) 解决方法
正如Cary Swoveland和vgoff所提到的,定义如
def foo arg1,*args,arg2 ... end 是可能的,所以你的最后一点不成立. 这取决于用例.如果该方法采用自然作为数组给出的参数,那么用户传递数组会更容易.例如,假设一个方法将backtrace_locations(array)作为其参数.那么最好有: def foo arg1,backtrace_locations,arg2 ... end foo("foo",$!.backtrace_locations,"bar") 而不是: def foo arg1,*backtrace_locations,*$!.backtrace_locations,"bar") 在其他情况下,当用户键入灵活数量的参数时,正如Sean Mackesey所指出的那样,当只有一个元素时,用户可能会忘记元素周围的[],所以最好这样做: def foo arg1,"e1","bar") foo("foo","e2","e3",args,["e1"],["e1","e3"],"bar") # => An error likely to happen (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |