Consider the following Ruby code that uses scan to find all matches of digits in a string. What will be printed?
text = "Order 123, item 456, code 789" matches = text.scan(/\d+/) puts matches.inspect
Remember that scan returns an array of strings matching the pattern.
The scan method finds all substrings matching the regex /\d+/, which means one or more digits. It returns them as strings in an array.
Given this Ruby code, what is the output of p result?
text = "Name: John, Age: 30; Name: Jane, Age: 25" result = text.scan(/Name: (\w+), Age: (\d+)/) p result
When scan uses capture groups, it returns an array of arrays with the captured parts.
The regex has two capture groups: one for the name and one for the age. scan returns an array of arrays, each inner array holding the captures for one match.
Look at this Ruby code snippet. It raises an error. What is the cause?
text = "abc123def456" matches = text.scan(/(\d+)/).map(&:to_i) puts matches
Check what scan returns when there are capture groups and how map(&:to_i) works on the result.
scan(/(\d+)/) returns an array of arrays: [["123"], ["456"]]. map(&:to_i) calls to_i on each inner array, but Array has no to_i method, raising NoMethodError.
Which Ruby code correctly finds all words starting with the letter 'a' in the string "apple banana apricot cherry"?
text = "apple banana apricot cherry"Use word boundary \b and match words starting with 'a'. Case sensitivity matters.
Option D matches words starting with 'a' using \b for word boundary and a\w* for words starting with 'a'. Option D misses the word boundary, so it matches 'a' anywhere. Option D matches any word starting with any letter. Option D matches words starting with 'A' or 'a' but uses case-insensitive flag which is not required here.
You have a string containing emails: "user1@example.com, admin@test.org, guest@domain.net". Which Ruby code extracts only the usernames (the part before '@') using scan?
emails = "user1@example.com, admin@test.org, guest@domain.net"Use capture groups to get the username part before '@'. Flatten the result if needed.
Option B uses a capture group for the username and matches the full email pattern. scan returns an array of arrays, so flatten is needed to get a simple array of usernames. Option B returns full emails. Option B tries to capture username with '@' included and then removes '@' manually. Option B returns array of arrays but without flattening, so the result is nested.