Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Passing an array to starts_with?

I want to check if my url starts with certain strings to save it on to a database afterwards. The strings are stored in an array and since starts_with? accepts multiple values, I want to get all array values in 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)

So my question is how to pass the array values to starts_with? And how to check if save_url is true. I'm not that good at arrays and loops in Ruby so any help is appreciated!

like image 916
GoYoshi Avatar asked Jul 20 '16 16:07

GoYoshi


2 Answers

You can try putting array with splat operator(*) like so:

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
like image 107
Surya Avatar answered Sep 18 '22 16:09

Surya


You could pass the array of URLs as follows to the start_with? method.

save_url = url.start_with?(*array)
like image 21
Pragash Avatar answered Sep 18 '22 16:09

Pragash