marcamillion marcamillion - 1 year ago 68
Ruby Question

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

Say I have a string

, 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


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.

Answer Source
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

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download