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

and*_*ndy 1 ruby splat

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

start_with?([prefixes]+) ? true or false
Run Code Online (Sandbox Code Playgroud)

这对我来说看起来像一个数组,但事实并非如此.您可以传递单个字符串或各种字符串作为参数,如下所示:

"hello".start_with?("heaven", "hell")     #=> true
Run Code Online (Sandbox Code Playgroud)

如何将数组作为参数列表传递?以下不起作用:

"hello".start_with?(["heaven", "hell"])
Run Code Online (Sandbox Code Playgroud)

mu *_*ort 7

括号是可选的文档约定,因此括号中

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

只是说你可以start_with?用零或更多来电话prefixes.这是文档中的常见约定,您将看到jQuery文档,Backbone文档,MDN JavaScript文档以及几乎任何其他软件文档.

如果你有一个你想要使用的前缀数组start_with?,那么你可以splat数组,从而unrayrayify它:

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