0
0
Rubyprogramming~10 mins

Capture groups in Ruby - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to capture the word 'cat' from the string.

Ruby
text = "The cat sat on the mat."
match = text.match(/[1]/)
puts match[0]
Drag options to blanks, or click blank then click option'
Adog
Bcat
Cmat
Dsat
Attempts:
3 left
💡 Hint
Common Mistakes
Using a word not present in the string.
Forgetting to put the pattern inside slashes.
2fill in blank
medium

Complete the code to capture the first word using a capture group.

Ruby
text = "Hello world"
match = text.match(/(\w+)[1]/)
puts match[1]
Drag options to blanks, or click blank then click option'
A\s
B\d
C\W
D\S
Attempts:
3 left
💡 Hint
Common Mistakes
Using \d which matches digits instead of whitespace.
Using \W which matches non-word characters.
3fill in blank
hard

Fix the error in the code to correctly capture the domain from the email.

Ruby
email = "user@example.com"
domain = email.match(/@(\w+[1]\w+)/)[1]
puts domain
Drag options to blanks, or click blank then click option'
A\d
B\s
C\W
D\.
Attempts:
3 left
💡 Hint
Common Mistakes
Not escaping the dot, causing it to match any character.
Using \s which matches whitespace instead of a dot.
4fill in blank
hard

Fill both blanks to capture the area code and the phone number separately.

Ruby
phone = "(123) 456-7890"
match = phone.match(/\(([1])\) ([2])-\d{4}/)
puts match[1]
puts match[2]
Drag options to blanks, or click blank then click option'
A\d{3}
B\w+
D\s
Attempts:
3 left
💡 Hint
Common Mistakes
Using \w+ which matches letters and digits, not just digits.
Forgetting to match the space between parts.
5fill in blank
hard

Fill all three blanks to create a hash with keys as captured words and values as their lengths.

Ruby
text = "red blue green"
result = text.scan(/(\w+) (\w+) (\w+)/).map do |[1], [2], [3]|
  { [1] => [1].length, [2] => [2].length, [3] => [3].length }
end
puts result
Drag options to blanks, or click blank then click option'
Aa
Bb
Cc
Dx
Attempts:
3 left
💡 Hint
Common Mistakes
Using the same variable name for all three captures.
Not matching the block parameters with the capture groups.