Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an element of an array partly exists in a given string

Tags:

arrays

ruby

I have a line of text

this is the line

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

['hey', 'format', 'qouting', 'this']

is a part of the string given above.

So for the line above it should return true.

For this line hello my name is martin it should not.

I know include? but I don't know how to use it here if it helps at all.

like image 694
Martin Klepsch Avatar asked Mar 30 '11 06:03

Martin Klepsch


People also ask

How do you check if an array contains part of a string?

You can use the includes() method in JavaScript to check if an item exists in an array. You can also use it to check if a substring exists within a string. It returns true if the item is found in the array/string and false if the item doesn't exist.

How do you check if an array contains a specific value?

JavaScript Array includes() The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found.

How do you find if an array contains a specific string in TypeScript?

Use the includes() method to check if an array contains a value in TypeScript, e.g. if (arr. includes('two')) {} . The includes method will return true if the value is contained in the array and false otherwise. Copied!

How do you check if an array contains a certain element in Java?

contains() method in Java is used to check whether or not a list contains a specific element. To check if an element is in an array, we first need to convert the array into an ArrayList using the asList() method and then apply the same contains() method to it​.


1 Answers

>> s = "this is the line"
=> "this is the line"
>> ['hey', 'format', 'qouting', 'this'].any? { |w| s =~ /#{w}/ }
=> true
>> ['hey', 'format', 'qouting', 'that'].any? { |w| s =~ /#{w}/ }
=> false
>> s2 = 'hello my name is martin'
=> "hello my name is martin"
>> ['hey', 'format', 'qouting', 'this'].any? { |w| s2 =~ /#{w}/ }
=> false
like image 183
Michael Kohl Avatar answered Oct 21 '22 00:10

Michael Kohl