Bird
0
0

You want to write a regex literal in Ruby that matches strings starting with "cat" or "dog". Which regex literal achieves this?

hard📝 Application Q8 of 15
Ruby - Regular Expressions
You want to write a regex literal in Ruby that matches strings starting with "cat" or "dog". Which regex literal achieves this?
A/^(cat|dog)$/
B/cat|dog$/
C/cat|dog/
D/^(cat|dog)/
Step-by-Step Solution
Solution:
  1. Step 1: Understand anchors and alternation

    ^ means start of string, $ means end. (cat|dog) means either 'cat' or 'dog'.
  2. Step 2: Evaluate options

    /^(cat|dog)/ matches strings starting with 'cat' or 'dog'. /cat|dog$/ matches 'cat' anywhere or 'dog' at end. /cat|dog/ matches 'cat' or 'dog' anywhere. /^(cat|dog)$/ matches exactly 'cat' or 'dog' only.
  3. Final Answer:

    /^(cat|dog)/ -> Option D
  4. Quick Check:

    Use ^ and (cat|dog) to match start with either word [OK]
Quick Trick: Use ^(cat|dog) to match start with 'cat' or 'dog' [OK]
Common Mistakes:
  • Misplacing anchors ^ and $
  • Not grouping alternatives with parentheses
  • Assuming | has higher precedence than anchors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes