0
0
Rubyprogramming~3 mins

Why Scan for all matches in Ruby? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could find every hidden word in a text with just one simple command?

The Scenario

Imagine you have a long paragraph and you want to find every time a certain word appears. Doing this by reading and checking each word one by one is like searching for a needle in a haystack by hand.

The Problem

Manually checking each word is slow and tiring. You might miss some matches or count some twice. It's easy to make mistakes and it takes a lot of time, especially if the text is very long.

The Solution

Using the scan method in Ruby lets you quickly find all matches of a pattern in a string. It does the hard work for you, returning all matches at once, so you don't have to check each word yourself.

Before vs After
Before
words = text.split(' ')
matches = []
words.each do |word|
  matches << word if word == 'ruby'
end
After
matches = text.scan(/ruby/)
What It Enables

It makes finding all occurrences of a pattern in text fast, easy, and error-free.

Real Life Example

Say you want to find every hashtag in a tweet. Using scan, you can grab all hashtags instantly without missing any.

Key Takeaways

Manually searching text is slow and error-prone.

scan finds all matches quickly and accurately.

This saves time and reduces mistakes when working with text.