Bird
Raised Fist0
Rubyprogramming~10 mins

Regex literal syntax (/pattern/) in Ruby - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Regex literal syntax (/pattern/)
Start
↓
Write /pattern/
↓
Ruby reads /pattern/
↓
Create Regex object
↓
Use Regex for matching
↓
Return match result or nil
↓
End
Ruby reads the pattern between slashes as a Regex object, then uses it to match strings, returning match info or nil.
Execution Sample
Ruby
text = "hello123"
pattern = /\d+/  # digits
match = text.match(pattern)
puts match[0] if match
This code finds the first group of digits in the text and prints it.
Execution Table
StepCode LineActionVariable StatesOutput
1text = "hello123"Assign string to texttext='hello123'
2pattern = /\d+/Create Regex object for digitspattern=/\d+/
3match = text.match(pattern)Match digits in textmatch=#<MatchData "123">
4puts match[0] if matchPrint matched digitsmatch=#<MatchData "123">123
5EndNo more codetext='hello123', pattern=/\d+/, match=#<MatchData "123">
💡 Reached end of code after printing matched digits
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4Final
textnil"hello123""hello123""hello123""hello123""hello123"
patternnilnil/\d+//\d+//\d+//\d+/
matchnilnilnil#<MatchData "123">#<MatchData "123">#<MatchData "123">
Key Moments - 2 Insights
Why do we write the pattern between slashes (/pattern/) instead of quotes?
In Ruby, slashes create a Regex object directly, unlike quotes which create strings. See step 2 in execution_table where /\d+/ becomes a Regex.
What happens if the pattern does not match the text?
The match variable becomes nil, so the condition 'if match' prevents errors. This is shown in step 3 where match would be nil if no digits found.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3, what is the value of 'match'?
A"123"
Bnil
C#<MatchData "123">
D/\d+/
💡 Hint
Check the 'Variable States' column at step 3 in execution_table.
At which step does Ruby create the Regex object?
AStep 2
BStep 1
CStep 3
DStep 4
💡 Hint
Look for when 'pattern' changes from nil to /\d+/ in variable_tracker and execution_table.
If the text was "hello" (no digits), what would 'match' be at step 3?
A#<MatchData "">
Bnil
C"hello"
D/\d+/
💡 Hint
Recall that match is nil if no pattern found, as explained in key_moments second question.
Concept Snapshot
Regex literal syntax in Ruby:
- Write pattern between slashes: /pattern/
- Creates a Regex object directly
- Use with String#match to find matches
- Returns MatchData or nil
- Example: /\d+/ matches digits
Full Transcript
This example shows how Ruby reads a regex literal written between slashes, like /\d+/, to create a Regex object. The code assigns a string to 'text', then creates a regex pattern to find digits. Using 'text.match(pattern)', Ruby searches for digits and returns a MatchData object if found. The program prints the matched digits '123'. If no match is found, 'match' would be nil, and the print is skipped. This step-by-step trace helps understand how regex literals work in Ruby.

Practice

(1/5)
1. What is the correct way to write a regex literal in Ruby to match the word cat?
easy
A. regex('cat')
B. "cat"
C. 'cat'
D. /cat/

Solution

  1. Step 1: Understand regex literal syntax

    In Ruby, regex literals are written between slashes, like /pattern/.
  2. Step 2: Identify the correct pattern for 'cat'

    The pattern to match the word 'cat' is simply /cat/.
  3. Final Answer:

    /cat/ -> Option D
  4. Quick Check:

    Regex literal = /pattern/ [OK]
Hint: Regex literals always use slashes /pattern/ in Ruby [OK]
Common Mistakes:
  • Using quotes instead of slashes
  • Calling a non-existent regex() function
  • Confusing string and regex syntax
2. Which of the following is the correct regex literal to match the word Dog case-insensitively in Ruby?
easy
A. /Dog/m
B. /Dog/g
C. /Dog/i
D. /Dog/

Solution

  1. Step 1: Identify the case-insensitive option

    In Ruby regex, the i option after the slashes makes matching case-insensitive.
  2. Step 2: Check the options given

    Only /Dog/i uses the correct i flag for case-insensitive matching.
  3. Final Answer:

    /Dog/i -> Option C
  4. Quick Check:

    Case-insensitive flag = i [OK]
Hint: Use /pattern/i for case-insensitive regex in Ruby [OK]
Common Mistakes:
  • Using g or m flags which mean different things
  • Omitting the i flag for case-insensitivity
  • Placing flags inside the slashes
3. What will be the output of this Ruby code?
text = "Hello World"
match = text =~ /world/i
puts match
medium
A. nil
B. 6
C. 0
D. Error

Solution

  1. Step 1: Understand the =~ operator with regex

    The operator =~ returns the index of the first match or nil if no match.
  2. Step 2: Analyze the regex and string

    The regex /world/i matches 'World' ignoring case. In "Hello World", 'World' starts at index 6 (0-based).
  3. Final Answer:

    6 -> Option B
  4. Quick Check:

    Case-insensitive match index = 6 [OK]
Hint: =~ returns match start index or nil if no match [OK]
Common Mistakes:
  • Ignoring case-insensitive flag i
  • Thinking output is true/false instead of index
  • Assuming match starts at 0 always
4. Identify the error in this Ruby regex literal:
pattern = /hello/i/
medium
A. Extra slash at the end causes syntax error
B. Missing quotes around pattern
C. Missing i flag for case-insensitivity
D. Regex literals cannot have flags

Solution

  1. Step 1: Check regex literal syntax

    A regex literal starts and ends with a single slash. Here, there is an extra slash at the end.
  2. Step 2: Identify the syntax error

    The extra slash after /hello/i is invalid and causes a syntax error.
  3. Final Answer:

    Extra slash at the end causes syntax error -> Option A
  4. Quick Check:

    Regex literal must start and end with one slash pair [OK]
Hint: Regex literals have exactly two slashes, no extras [OK]
Common Mistakes:
  • Adding extra slash after regex
  • Confusing regex with string quotes
  • Thinking flags go inside slashes
5. You want to find all words starting with a or A in a string using a regex literal. Which regex literal correctly matches this requirement?
hard
A. /\b[a]\w*/i
B. /\b[A]\w*/
C. /\b[a]\w*/
D. /\b[a-z]\w*/i

Solution

  1. Step 1: Understand the requirement

    We want words starting with 'a' or 'A'. Using case-insensitive flag i simplifies matching both.
  2. Step 2: Analyze options

    /\b[a]\w*/i uses /\b[a]\w*/i which matches word boundary, then 'a' (case-insensitive), then zero or more word chars. This matches words starting with 'a' or 'A'.
  3. Final Answer:

    /\b[a]\w*/i -> Option A
  4. Quick Check:

    Use i flag to match both 'a' and 'A' easily [OK]
Hint: Use /pattern/i to match letters ignoring case [OK]
Common Mistakes:
  • Listing both 'a' and 'A' inside brackets without i flag
  • Using wrong character classes
  • Missing word boundary \b
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