Skip to content

Instantly share code, notes, and snippets.

@eljojo
Created September 1, 2013 17:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eljojo/6405792 to your computer and use it in GitHub Desktop.
Save eljojo/6405792 to your computer and use it in GitHub Desktop.
String#each_match, kind of like String#scan but returning MatchData instead of the simple match. It takes a block as well!
class String
def each_match(regex)
result = []
position = 0
while match_data = regex.match(self, position) do
result << if block_given? then yield(match_data) else match_data end
position = match_data.end(match_data.size - 1)
end
result
end
end
@eljojo
Copy link
Author

eljojo commented Sep 1, 2013

'jojo'.each_match(/./) do |match|
  [match.pre_match, match[0], match.post_match].join('*')
end
# => ["*j*ojo", "j*o*jo", "jo*j*o", "joj*o*"]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment