Ruby:将数组传递给starts_with?

GoY*_*shi 7 ruby arrays loops ruby-on-rails

我想检查我的url是否以某些字符串开头,然后将其保存到数据库中.字符串存储在一个数组中,因为starts_with?接受多个值,我想获取所有数组值starts_with?.

array = ["www.example.com/content1", "www.example.com/content2", "www.example.com/content3"]

save_url = url.starts_with?() #here I want to insert all array values, but how?

if save_url #I want to check if save_url is true so my entries are somewhat filtered
DBTable.create(url: url)
Run Code Online (Sandbox Code Playgroud)

所以我的问题是如何将数组值传递给starts_with?以及如何检查save_url是否为true.我不擅长Ruby中的数组和循环,所以任何帮助都值得赞赏!

Sur*_*rya 15

您可以尝试使用splat operator(*)来放置数组,如下所示:

url = 'www.example.com/content1/test.html'# => "www.example.com/content1/test.html"
array = ["www.example.com/content1", "www.example.com/content2", "www.example.com/content3"]
save_url = url.starts_with?(*array) #=> true
Run Code Online (Sandbox Code Playgroud)

  • 深入了解如何/为何如此有效,请查看http://blog.honeybadger.io/ruby-splat-array-manipulation-destructuring/ (2认同)