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!
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 indices0
and6
.
The result should be:
Ruby1[ 2 "The substring 'loW' was found in the original string 'HelloWorld' at position(s) 3.", 3 "The substring 'ear' was found in the original string 'LearningRuby' at position(s) 1.", 4 "The substring 'o' was found in the original string 'GoForBroke' at position(s) 1, 3, 7.", 5 "The substring 'Ba' was found in the original string 'BackToBasics' at position(s) 0, 6." 6]
Let’s break this task down into manageable steps.
Start by creating an empty array to store the results. This array will eventually hold formatted strings describing the occurrences of each substring.
Ruby1def find_substring(orig_strs, substrs) 2 result_arr = []
The result_arr
will collect our findings in a clear and readable format.
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.
Ruby1 orig_strs.zip(substrs).each do |original, substring| 2 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
.
To locate every occurrence of the substring, use a while
loop. Continue searching until no further matches are found (start_pos
becomes nil
). Track each occurrence in an array called match_indices
and update start_pos
to search for the next occurrence:
Ruby1 match_indices = [] 2 while start_pos 3 match_indices << start_pos 4 start_pos = original.index(substring, start_pos + 1) 5 end
This ensures you find all matches without restarting the search from the beginning.
Format the results for readability, then append the formatted string to result_arr
:
Ruby1 result_arr << "The substring '#{substring}' was found in the original string '#{original}' at position(s) #{match_indices.join(', ')}." 2 end
The join(', ')
ensures that multiple indices are presented as a comma-separated list.
Here is the complete method, integrating all the steps:
Ruby1def find_substring(orig_strs, substrs) 2 result_arr = [] 3 4 orig_strs.zip(substrs).each do |original, substring| 5 start_pos = original.index(substring) 6 match_indices = [] 7 while start_pos 8 match_indices << start_pos 9 start_pos = original.index(substring, start_pos + 1) 10 end 11 result_arr << "The substring '#{substring}' was found in the original string '#{original}' at position(s) #{match_indices.join(', ')}." 12 end 13 14 result_arr 15end 16 17# Example Usage 18orig_strs = ["HelloWorld", "LearningRuby", "GoForBroke", "BackToBasics"] 19substrs = ["loW", "ear", "o", "Ba"] 20 21puts find_substring(orig_strs, substrs)
This outputs:
Ruby1[ 2 "The substring 'loW' was found in the original string 'HelloWorld' at position(s) 3.", 3 "The substring 'ear' was found in the original string 'LearningRuby' at position(s) 1.", 4 "The substring 'o' was found in the original string 'GoForBroke' at position(s) 1, 3, 7.", 5 "The substring 'Ba' was found in the original string 'BackToBasics' at position(s) 0, 6." 6]
Great job! You’ve successfully created a method to locate and format all occurrences of substrings within strings. This lesson taught you how to:
- Use Ruby’s
index
method to find substring positions. - Implement loops to handle multiple occurrences of substrings.
- Format output for clarity.
Keep practicing similar problems to refine your skills. The more you experiment, the stronger your grasp of string manipulation and iteration in Ruby will become. Happy coding!