Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scanning an array of strings for match in Ruby

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?

like image 973
prabu Avatar asked Apr 10 '13 14:04

prabu


People also ask

How do you check if an array is equal in Ruby?

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.

How do you split an array of strings in Ruby?

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.

How do you slice an array in Ruby?

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.

What does .first do in Ruby?

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.


2 Answers

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.

like image 102
the Tin Man Avatar answered Sep 29 '22 11:09

the Tin Man


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
like image 26
Arup Rakshit Avatar answered Sep 29 '22 11:09

Arup Rakshit