How to Check Whether a String Contains a Substring in Ruby

How to check whether a string contains a substring in Ruby

You can use the include? method:

my_string = "abcdefg"
if my_string.include? "cde"
puts "String includes 'cde'"
end

How to tell if a string contains a substring

def the_in_the_kitchen(string)
return string.match?(/the \w+ is in the kitchen/i)
end

This should work. I've used a regexp, and replace the word cat or dog by \w+, which means a serie of letters. I've also added the i flag to the regexp, it stands for ignore case. Hence The DOG iS In ThE KITchen would work as well.

How can I tell if my string contains a substring from an array?

Given:

arr = ["a", "b", "x"]
str = "DoDox"

EDIT: As the other comments have pointed out, this is actually the fastest way, as it breaks the evaluation when a single true statement is found:

arr.any?{|substr| str.include?(substr)}

The foldl way: I have used this example to illustrate the power of folding expresions. This solution might be somewhat elegant as an illustrative example for foldings, but it is not sufficiently performant.

arr.map{|substr| str.include?(substr)}.inject{|x,y| x || y}

The map-function maps all possible substrings the original string str can have. inject iterates over the returning array and compares its constituents, using a logical or. If any substring in the array 'arr' is encountered, the result will yield true in the result of map. With the or-relation we return a true value, if any value of the result of map was true. This is slower than any?, because every single value in the array gets evaluated even if a true is encountered (wich would always yield a true at the end of inject).

["a", "b", "x"] -------> [false, false, true] ----------> true
map() inject()

Check whether a string contains one of multiple substrings

Try parens in the expression:

 haystack.include?(needle1) || haystack.include?(needle2)

Check if string contains substring in array AND get the match

str = "foobazbar"
arr = ["baz", "clowns"]
result = arr.find { |s| str.include?(s) }

result at this point is the first element in arr that is a substring of str or is nil

Check if a string contains any substrings from an array

Your solution is efficient, it's just not as expressive as Ruby allows you to be. Ruby provides the Enumerable#any? method to express what you are doing with that loop:

words.any? { |word| sentence.include?(word) }

Check whether a string contains all the characters of another string in Ruby

Sets and array intersection don't account for repeated chars, but a histogram / frequency counter does:

require 'facets'

s1 = "aasmflathesorcerersnstonedksaottersapldrrysaahf"
s2 = "harrypotterandtheasorcerersstone"
freq1 = s1.chars.frequency
freq2 = s2.chars.frequency
freq2.all? { |char2, count2| freq1[char2] >= count2 }
#=> true

Write your own Array#frequency if you don't want to the facets dependency.

class Array
def frequency
Hash.new(0).tap { |counts| each { |v| counts[v] += 1 } }
end
end

Check whether a string contains numbers

If its certain that the format of the valid personname is always

<string>.<number>.<string>

You can try using :[regex, index] method for strings in ruby.

https://ruby-doc.org/core-2.6.1/String.html#method-i-5B-5D

So if

personname = "devid.123.devid"

s[/(.*)(\.\d+\.)(.*)/, 2] = ".123."

There are three different groups in the regex (.*)(\.\d+\.)(.*).

  1. Matches anything
  2. Matches a .<number>.
  3. Matches anything

So based on this regex, the second group should provide you .<number>. which, I hope, is what you need.

Tested with Ruby 2.4.1



Related Topics



Leave a reply



Submit