2

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"?

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.

2 Answers 2

5
urls.flatten.all?{|s| s.start_with?("http://s3.amazonaws.com")}
Sign up to request clarification or add additional context in comments.

Comments

4

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

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

6 Comments

Good point about using a predefined string (and for avoiding an intermediate array). However, you can do that also by using the freeze optimization in string literals. start_with?("http://s3.amazonaws.com".freeze).
You're right about freeze. In that case I wanted to avoid temporary array, because it requires 2 iterations (the first to create it, and the second to verify predicate).
Work's great, thank you, but the problem now is that compare_against = ["http://s3.amazonaws.com", Rails.root] , and I tried with each inside but every time is true
explain, what in your context compare_against = ["http://s3.amazonaws.com", Rails.root] means. Whether it's enough if string starts with any of compare_against, or it has to match all of them
If my string start with s3.amazonaws.com or RAILS.root (RAILS.root is current url domain) should return true.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.