8

I have an array:

a = ["http://design.example.com", "http://www.domcx.com", "http://subr.com"]

and then I want to return true if one of the elements in that array matches the string:

s = "example.com"

I tried with include? and any?.

a.include? s
a.any?{|w| s=~ /#{w}/}

I don't know how to use it here. Any suggestions?

2 Answers 2

8

You can use any? like:

[
  "http://design.example.com",
  "http://www.domcx.com",
  "http://subr.com"
].any?{ |s| s['example.com'] }

Substituting your variable names:

a = [
  "http://design.example.com",
  "http://www.domcx.com",
  "http://subr.com"
]
s = "example.com"
a.any?{ |i| i[s] }

You can do it several other ways also, but the advantage using any? is it will stop as soon as you get one hit, so it can be much faster if that hit occurs early in the list.

Sign up to request clarification or add additional context in comments.

3 Comments

See str[matchstr]. "If a match_str is given, that string is returned if it occurs in the string." It returns nil if nothing is found, or the sub-string, effectively triggering the any? with a false/true result. It's part of the wonderfulness of Ruby.
Thanks for the link,never reached to the middle of the cluster of methods :)
Thanks for the match str method. your logic works for me. I need to get very first element in an array list if it is return true. I have written like a.any?{ |i| p i unless i[s] }. Thanks.
2

How is the below:

a=["http://design.example.com", "http://www.domcx.com", "http://subr.com"]
s= "sus"
p a.any? { |w| w.include? s } #=> false

a=["http://design.example.com", "http://www.domcx.com", "http://subr.com"]
s= "design.example"
p a.any? { |w| w.include? s } #=>true

a=["http://design.example.com", "http://www.domcx.com", "http://subr.com"]
s= "desingn.example"
p a.any? { |w| w.include? s } #=>false

a=["http://design.example.com", "http://www.domcx.com", "http://subr.com"]
s= "example"
p a.any? { |w| w.include? s } #=>true

a=["http://design.example.com", "http://www.domcx.com", "http://subr.com"]
s= "example.com"
p a.any? { |w| w.include? s } #=>true

Comments

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.