How to Use scan Method in Ruby: Syntax and Examples
In Ruby, the
scan method is used on strings to find all occurrences of a pattern and return them as an array. You can pass a string or regular expression to scan, and it will extract all matching parts from the original string.Syntax
The scan method is called on a string and takes one argument: a pattern to search for. This pattern can be a string or a regular expression.
- String: Finds exact matches of the substring.
- Regexp: Finds all matches that fit the pattern.
The method returns an array of all matches found.
ruby
string.scan(pattern) # pattern can be a String or Regexp
Example
This example shows how to use scan to find all words and all digits in a string.
ruby
text = "I have 2 apples and 3 bananas." words = text.scan(/\w+/) numbers = text.scan(/\d+/) puts "Words: #{words}" puts "Numbers: #{numbers}"
Output
Words: ["I", "have", "2", "apples", "and", "3", "bananas"]
Numbers: ["2", "3"]
Common Pitfalls
One common mistake is expecting scan to return a single match or a boolean. Instead, it always returns an array of all matches, which can be empty if no matches are found.
Another pitfall is using scan with capturing groups in the pattern. When groups are used, scan returns an array of arrays with the captured parts, not the full match.
ruby
text = "abc123def456" # Without groups, returns full matches p text.scan(/\d+/) # => ["123", "456"] # With groups, returns captured parts p text.scan(/(\d)(\d)(\d)/) # => [["1", "2", "3"], ["4", "5", "6"]]
Output
["123", "456"]
[["1", "2", "3"], ["4", "5", "6"]]
Quick Reference
Summary tips for using scan:
- Use a string pattern for exact substring matches.
- Use a regular expression for flexible pattern matching.
- Remember
scanreturns an array of all matches. - If your regex has groups,
scanreturns arrays of captured groups. - Use
flattenif you want a single array of all captured parts.
Key Takeaways
The scan method extracts all matches of a pattern from a string and returns them as an array.
You can use either a string or a regular expression as the pattern argument.
If your pattern includes capturing groups, scan returns an array of arrays with captured parts.
scan never returns nil; it returns an empty array if no matches are found.
Use scan to easily find all occurrences of substrings or patterns in text.