检查数组中的所有值是否以字符串开头

时间:2023-01-14 20:11:16

I have an array of links:

我有一系列链接:

urls =
[
  ["http://s3.amazonxaws.com/bb_images/uk/media_images/2/1-veXRiLqrxPbguaxFIcFbPA.png"],
  ["http://s3.amazonaws.com/bb_images/uk/media_images/2/1-veXRiLqrxPbguaxFIcFbPA.png"]
]

How can I return true if all links start with "http://s3.amazonaws.com"?

如果所有链接都以“http://s3.amazonaws.com”开头,我如何返回true ?

I tried:

我试着:

if urls.any? { |url| url.include?('http://s3.amazonaws.com/') }
     #execute code
else
     #execute else code
end

But it does not return true or false in cases.

但在某些情况下,它不会返回true或false。

2 个解决方案

#1


3  

@sawa's code works. However, the following is a more efficient version.

@sawa的代码工作。然而,下面是一个更有效的版本。

compare_against = "http://s3.amazonaws.com"
urls.all?{|url_array| url_array[0].start_with?(compare_against)}

#2


4  

urls.flatten.all?{|s| s.start_with?("http://s3.amazonaws.com")}

#1


3  

@sawa's code works. However, the following is a more efficient version.

@sawa的代码工作。然而,下面是一个更有效的版本。

compare_against = "http://s3.amazonaws.com"
urls.all?{|url_array| url_array[0].start_with?(compare_against)}

#2


4  

urls.flatten.all?{|s| s.start_with?("http://s3.amazonaws.com")}