Bird
Raised Fist0
Rubyprogramming~10 mins

Common patterns and character classes in Ruby - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Common patterns and character classes
Start
↓
Define regex pattern
↓
Use character classes
↓
Match string with pattern?
No→No match
Yes↓
Extract or use matched data
↓
End
This flow shows how a regex pattern with character classes is defined and used to match strings, then extract or use the matched parts.
Execution Sample
Ruby
pattern = /[a-zA-Z]+/  # letters only
text = "Hello123"
match = text.match(pattern)
puts match[0] if match
This Ruby code finds the first sequence of letters in the text and prints it.
Execution Table
StepActionPatternInput StringMatch ResultOutput
1Define pattern/[a-zA-Z]+/"Hello123"N/AN/A
2Match pattern to string/[a-zA-Z]+/"Hello123""Hello"N/A
3Check if match existsN/AN/AMatch foundN/A
4Print matched substringN/AN/A"Hello"Hello
5EndN/AN/AN/AN/A
💡 Matching stops after first letter sequence found; rest of string ignored.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
patternundefined/[a-zA-Z]+//[a-zA-Z]+//[a-zA-Z]+//[a-zA-Z]+/
textundefined"Hello123""Hello123""Hello123""Hello123"
matchnilMatchData("Hello")MatchData("Hello")MatchData("Hello")MatchData("Hello")
outputundefinedundefinedundefined"Hello""Hello"
Key Moments - 3 Insights
Why does the pattern /[a-zA-Z]+/ only match 'Hello' and not the numbers?
Because the character class [a-zA-Z] matches only letters, and + means one or more letters in a row. Numbers are not letters, so matching stops before digits. See execution_table step 2.
What happens if the input string starts with numbers, like '123Hello'?
The pattern will not match at the start because it expects letters first. The match method finds the first substring matching the pattern anywhere, so it will match 'Hello' later. This is shown by the pattern behavior in step 2.
Why do we check if match exists before printing?
Because if no match is found, match will be nil and trying to access match[0] causes an error. Checking prevents errors. See execution_table step 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 2, what substring does the pattern match in "Hello123"?
A"123"
B"Hello123"
C"Hello"
D"" (empty string)
💡 Hint
Check the 'Match Result' column at step 2 in execution_table.
At which step do we confirm that a match was found before printing?
AStep 1
BStep 3
CStep 4
DStep 5
💡 Hint
Look at the 'Action' column in execution_table where match existence is checked.
If the input string was "123Hello", what would the match result be at step 2?
A"Hello"
Bnil (no match)
C"123"
D"123Hello"
💡 Hint
Remember the pattern matches letters only, so it skips initial digits and finds letters later.
Concept Snapshot
Ruby regex uses character classes like [a-zA-Z] to match letters.
+ means one or more repetitions.
.match returns first match or nil.
Always check if match exists before using it.
Character classes help target specific groups of characters.
Full Transcript
This example shows how Ruby uses regular expressions with character classes to find patterns in text. We define a pattern that matches one or more letters using [a-zA-Z]+. When we apply this pattern to the string "Hello123", it matches the first sequence of letters "Hello" and ignores the numbers. We check if a match was found before printing to avoid errors. This process helps extract specific parts of text based on character types.

Practice

(1/5)
1. Which Ruby regular expression pattern matches any single digit character?
easy
A. /\D/
B. /\d/
C. /\s/
D. /\w/

Solution

  1. Step 1: Understand \d in Ruby regex

    The pattern \d matches any digit character (0-9).
  2. Step 2: Compare with other options

    \w matches word characters (letters, digits, underscore), \s matches whitespace, \D matches non-digit characters.
  3. Final Answer:

    /\d/ -> Option B
  4. Quick Check:

    Digit pattern = /\d/ [OK]
Hint: Remember \d means digit, \w means word character [OK]
Common Mistakes:
  • Confusing \d with \w
  • Using /\D/ which matches non-digits
  • Thinking \s matches digits
2. Which of the following is the correct Ruby syntax to match any word character one or more times?
easy
A. /\w+/
B. /\w*/
C. /\w?/
D. /\w{}/

Solution

  1. Step 1: Understand quantifiers in regex

    + means one or more times, * means zero or more, ? means zero or one.
  2. Step 2: Apply to \w

    /\w+/ matches one or more word characters, which is the correct syntax.
  3. Final Answer:

    /\w+/ -> Option A
  4. Quick Check:

    One or more word chars = /\w+/ [OK]
Hint: Use + for one or more matches in regex [OK]
Common Mistakes:
  • Using * which allows zero matches
  • Using ? which allows zero or one match
  • Using empty braces {} which is invalid
3. What is the output of this Ruby code?
text = "Room 101"
match = text.match(/\d+/)
puts match[0]
medium
A. 101
B. Room
C. 1
D. nil

Solution

  1. Step 1: Understand the regex /\d+/

    This pattern matches one or more digits in a row.
  2. Step 2: Apply match to string "Room 101"

    The digits "101" are matched as a group, so match[0] returns "101".
  3. Final Answer:

    101 -> Option A
  4. Quick Check:

    Digits matched = 101 [OK]
Hint: \d+ grabs all digits in a row, not just one [OK]
Common Mistakes:
  • Thinking it matches only one digit
  • Confusing match[0] with match object
  • Expecting the word part instead of digits
4. Find the error in this Ruby code snippet:
email = "user@example.com"
if email =~ /\w+@\w+.\w+/
  puts "Valid email"
else
  puts "Invalid email"
end
medium
A. The regex should use \d instead of \w
B. The =~ operator is used incorrectly
C. The regex does not escape the dot properly
D. The string should be in single quotes

Solution

  1. Step 1: Examine the regex pattern

    The pattern /\w+@\w+.\w+/ uses an unescaped . which matches any character, not a literal dot.
  2. Step 2: Identify the error

    The dot after the domain must be escaped as \. to match the literal "." in email addresses.
  3. Final Answer:

    The regex does not escape the dot properly -> Option C
  4. Quick Check:

    Escape literal dot as \. [OK]
Hint: Remember to escape dot as \. to match literal dot [OK]
Common Mistakes:
  • Thinking dot doesn't need escaping
  • Misusing =~ operator
  • Confusing \w with \d in email regex
5. You want to extract all words starting with a capital letter from the string "Hello World from Ruby". Which Ruby regex pattern should you use with scan?
hard
A. /\d+/
B. /\b[a-z]\w*/
C. /\s+/
D. /\b[A-Z]\w*/

Solution

  1. Step 1: Understand the requirement

    We want words starting with a capital letter, so first letter must be A-Z.
  2. Step 2: Analyze the regex options

    /\b[A-Z]\w*/ matches word boundary, then capital letter, then zero or more word chars.
  3. Step 3: Check other options

    /\b[a-z]\w*/ matches lowercase start, /\d+/ matches digits, /\s+/ matches spaces, so they don't fit.
  4. Final Answer:

    /\b[A-Z]\w*/ -> Option D
  5. Quick Check:

    Capital-start words = /\b[A-Z]\w*/ [OK]
Hint: Use \b for word boundary and [A-Z] for capital letters [OK]
Common Mistakes:
  • Using [a-z] instead of [A-Z]
  • Forgetting word boundary \b
  • Using digit or space patterns incorrectly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard