【发布时间】:2014-05-05 09:28:06
【问题描述】:
Ruby 是一门很棒的语言,有时让我感到困惑(因为我没有那么出色)。 splat 争论是造成这种混乱的原因。所以请赐教。
给定以下方法:
def doSomething(with_this, *and_that)
# ...
end
您可以使用 选项 1 调用该方法:
doSomething("With this", "index 0", "index 1", "etc")
或使用选项 2:
an_array = ["index 0", "index 1", "etc"]
doSomething("With this", *an_array)
但是如果我的方法是这样定义的呢:
def doSomething(with_this, *and_that, and_even_that)
# ...
end
注意splat参数后有一个参数
问题 1:除了使用以下方式之外,还有其他方法可以为 and_even_that 添加参数吗?
an_array = ["index 0", "index 1", "etc"]
doSomething("With this", *an_array, "With that")
在追求成为一名优秀的 Ruby 程序员的过程中,我也想知道这些:
额外问题:
最好不要在方法定义中使用多个 splat 参数吗?
在方法定义中将 splat 参数留到最后是最佳做法吗?
提前谢谢你。
【问题讨论】:
标签: ruby arrays function methods