scan returns an empty array

From the scan docs.

If the pattern contains no groups, each individual result consists of the matched string, $&. If the pattern contains groups, each individual result is itself an array containing one entry per group.

By adding the parentheses to the middle of your regex, you created a capturing group. Scan will return whatever that group captures. In the example you gave, it will be 'u'.

"Rahul\n \n\n \n Nov 6\n\n\n ・2 min read".scan(/\A\w+(\s|\w)\w+/) #=> [["u"]]

The group can be marked as non-capturing to return to your old implementation

"Rahul\n \n\n \n Nov 6\n\n\n ・2 min read".scan(/\A\w+(?:\s|\w)\w+/) #=> ["Rahul"]
#                                                       ^

Or you can add a named capture group to what you actually want to extract.

"Rahul\n \n\n \n Nov 6\n\n\n ・2 min read".match(/\A(?<name>\w+(\s|\w)\w+)/)[:name] #=> "Rahul"

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top