Look at this Ruby code using regex. What will it print?
text = "Hello Ruby 2024!" match = text.match(/Ruby (\d{4})/) puts match[1]
Remember, parentheses in regex capture groups. What does match[1] return?
The regex /Ruby (\d{4})/ looks for 'Ruby ' followed by exactly 4 digits. The parentheses capture those digits. match[1] returns the first captured group, which is '2024'.
Choose the best reason why regex is powerful in Ruby.
Think about how Ruby lets you use regex without extra setup.
Ruby has built-in regex support with special syntax and methods, making it easy and powerful for text matching and extraction.
Find the error when running this Ruby code:
pattern = /\d{3}-\d{2}-\d{4}/
text = "My number is 123-45-6789"
match = text.match(pattern)
puts match[5]Check what match[5] means if the regex has fewer capture groups.
The regex has no capture groups, so match[5] tries to access a non-existent group index, causing an IndexError.
Choose the Ruby code that correctly finds all words starting with 'a' in a string.
Remember, \b means word boundary and \w* means zero or more word characters.
Option D matches a word boundary, then 'a', then zero or more word characters, correctly capturing words starting with 'a'.
This Ruby code uses regex with named capture groups. What is the value of result?
text = "User: alice, ID: 42" pattern = /User: (?<name>\w+), ID: (?<id>\d+)/ match = text.match(pattern) result = {user: match[:name], id: match[:id].to_i}
Look at how the hash keys and values are created and the use of to_i.
The code creates a Ruby hash with symbol keys :user and :id. The id value is converted to an integer with to_i. So the result is {user: "alice", id: 42}.