Search code examples
rubystringstring-matching

How do I detect the presence of a substring in 1 string in another string?


Say I have a string "rubinassociatespa", what I would like to do is detect any substring of that string with 3 characters or more, in any other string.

For example, the following strings should be detected:

  • rubin
  • associates
  • spa
  • ass
  • rub etc.

But what should NOT be detected are the following strings:

  • rob
  • cpa
  • dea
  • ru or any other substring that does not appear in my original string, or is shorter than 3 characters.

Basically, I have a string and I am comparing many other strings against it and I only want to match the strings that comprise a substring of the original string.

I hope that's clear.


Solution

  • str = "rubinassociatespa"
    
    arr = %w| rubin associates spa ass rub rob cpa dea ru |
      #=> ["rubin", "associates", "spa", "ass", "rub", "rob", "cpa", "dea", "ru"]
    

    Just use String#include?.

    def substring?(str, s)
      (s.size >= 3) ? str.include?(s) : false
    end
    
    arr.each { |s| puts "#{s}: #{substring? str, s}" }
      # rubin: true
      # associates: true
      # spa: true
      # ass: true
      # rub: true
      # rob: false
      # cpa: false
      # dea: false
      # ru: false