如何将数组作为参数列表传递



Ruby的文档将方法签名显示为:

start_with?([prefixes]+) → true or false

看起来像一个数组,但它不是。您可以传递单个字符串或各种字符串作为参数,如下所示:

"hello".start_with?("heaven", "hell")     #=> true

如何传递一个数组作为参数列表?

"hello".start_with?(["heaven", "hell"])

括号是可选的文档约定,所以

中的括号

start_with?([prefixes]+) → true or false

表示可以用0个或多个prefixes调用start_with?。这是文档中的一个常见约定,您将在jQuery文档、Backbone文档、MDN JavaScript文档以及几乎所有其他软件文档中看到它。

如果您有一个希望与start_with?一起使用的前缀数组,那么您可以将该数组拆分为非数组:

a = %w[heaven hell]
'hello'.start_with?(*a)           # true
a = %w[where is]
'pancakes house?'.start_with?(*a) # false

最新更新