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?
Arrays can be equal if they have the same number of elements and if each element is equal to the corresponding element in the array. To compare arrays in order to find if they are equal or not, we have to use the == operator.
The general syntax for using the split method is string. split() . The place at which to split the string is specified as an argument to the method. The split substrings will be returned together in an array.
Ruby | Array slice() function Array#slice() : slice() is a Array class method which returns a subarray specified by range of indices. Return: a subarray specified by range of indices.
The first() is an inbuilt method in Ruby returns an array of first X elements. If X is not mentioned, it returns the first element only. Parameters: The function accepts X which is the number of elements from the beginning. Return Value: It returns an array of first X elements.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With