0
0
Rubyprogramming~15 mins

Scan for all matches in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Scan for all matches
📖 Scenario: Imagine you have a paragraph of text and you want to find all the words that start with the letter 'a'. This is useful when you want to highlight or count specific words in a text.
🎯 Goal: You will write a Ruby program that uses the scan method to find all words starting with the letter 'a' in a given string.
📋 What You'll Learn
Create a string variable called text with the exact sentence: "An apple a day keeps the doctor away."
Create a regular expression variable called pattern that matches words starting with the letter 'a' (case insensitive).
Use the scan method on text with pattern to find all matching words and store them in a variable called matches.
Print the matches array.
💡 Why This Matters
🌍 Real World
Finding all matches in text is useful for searching, filtering, or analyzing data like emails, logs, or documents.
💼 Career
Many programming jobs require text processing skills, including using regular expressions to extract information efficiently.
Progress0 / 4 steps
1
Create the text string
Create a string variable called text and set it to the exact sentence: "An apple a day keeps the doctor away."
Ruby
Need a hint?

Use double quotes around the sentence and assign it to text.

2
Create the pattern to match words starting with 'a'
Create a regular expression variable called pattern that matches words starting with the letter 'a' or 'A'. Use /\b[aA]\w*/ as the pattern.
Ruby
Need a hint?

The pattern /\b[aA]\w*/ matches words starting with 'a' or 'A'.

3
Find all matches using scan
Use the scan method on text with pattern to find all matching words and store them in a variable called matches.
Ruby
Need a hint?

Use text.scan(pattern) to get all words starting with 'a' or 'A'.

4
Print the matches
Print the matches array using puts matches.inspect to show all matched words.
Ruby
Need a hint?

Use puts matches.inspect to print the array of matches.