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:
- An array of "original" strings.
- 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 index3. - In
"LearningRuby","ear"starts at index1. - In
"GoForBroke","o"appears at indices1,3, and7. - In
"BackToBasics","Ba"starts at indices0and6.
The result should be:
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.
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.
Here, original.index(substring) finds the first occurrence of the substring within the string. If no match exists, it returns nil.
