ruby - 单个数组参数与多个参数

标签 ruby coding-style

我看到了这样定义和使用的方法:

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

为什么不直接使用数组作为第二个参数,而不是使用 splat 将参数组合成一个数组?

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)

最佳答案

splat 感觉很自然,因为这种方法可以合理地应用于单个或多个名称。需要在数组大括号中放置单个参数很烦人且容易出错,例如 mention('your courses rocked!', ['eallam'])。 splat 还经常节省击键次数,即使方法只适用于 Array

此外,您没有理由不能将其他参数放入*names:

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

关于ruby - 单个数组参数与多个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19439216/

相关文章:

c# - 在 C# 中隐藏大括号

ruby-on-rails - 显示用户可能没有的数据的最佳实践

ruby - 声明后分配哈希值

ruby-on-rails - 使用 Rails 验证,如何将短语列入白名单,例如 "Learn Ruby"

C - 客户端如何使用/访问多个实现?

ruby-on-rails - 连接被拒绝 - connect(2) for "localhost"port 1025 - Devise Mailer

types - Erlang 头文件 (.hrl) 中应该和不应该有什么?

java - 在 Intellij 中,如何在驼峰大小写和下划线分隔之间切换?

python - 对 Python `import x` 和 `from x import y` 语句进行排序的正确方法是什么?