Finding Substrings and Their Indices

Introduction

Welcome! In this lesson, we’ll delve into an essential aspect of string manipulations: identifying all occurrences of a substring within a larger string. This is a crucial skill with real-world applications like text processing and data analysis.

By the end of this lesson, you'll know how to systematically find and report substring matches using Ruby. Let's get started!

Task Statement and Description

You are tasked with creating a Ruby method called find_substring. This method will take two arrays as input:

  1. An array of "original" strings.
  2. An array of "substrings" to search for within the corresponding strings.

Your goal is to find all occurrences of each substring in its associated string and return a formatted list of results.

Consider these inputs:

  • Original List: ["HelloWorld", "LearningRuby", "GoForBroke", "BackToBasics"]
  • Substring List: ["loW", "ear", "o", "Ba"]

Expected Output:

  • In "HelloWorld", "loW" starts at index 3.
  • In "LearningRuby", "ear" starts at index 1.
  • In "GoForBroke", "o" appears at indices 1, 3, and 7.
  • In "BackToBasics", "Ba" starts at indices 0 and 6.

The result should be:

[
  "The substring 'loW' was found in the original string 'HelloWorld' at position(s) 3.",
  "The substring 'ear' was found in the original string 'LearningRuby' at position(s) 1.",
  "The substring 'o' was found in the original string 'GoForBroke' at position(s) 1, 3, 7.",
  "The substring 'Ba' was found in the original string 'BackToBasics' at position(s) 0, 6."
]

Let’s break this task down into manageable steps.

Step 1: Initialize the Output Array

Start by creating an empty array to store the results. This array will eventually hold formatted strings describing the occurrences of each substring.

def find_substring(orig_strs, substrs)
  result_arr = []

The result_arr will collect our findings in a clear and readable format.

Step 2: Pair Strings and Substrings

Using zip, combine the original strings with their corresponding substrings into pairs. Iterate through these pairs using each, and for each pair, locate all starting indices of the substring in the original string.

  orig_strs.zip(substrs).each do |original, substring|
    start_pos = original.index(substring)

Here, original.index(substring) finds the first occurrence of the substring within the string. If no match exists, it returns nil.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal