Last active
April 28, 2019 11:31
-
-
Save marshall-lee/615642d1ee57754e2e5ef0fc20bf10e9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def build(str) | |
str = str.dup | |
str.prepend '\A' | |
str.gsub! %r{/:([a-z]+)}, '/(?<\1>[^\/]+)' | |
str << '(?<format>\.[a-z]\w*)?' | |
str << '\z' | |
Regexp.new(str) | |
end | |
rx = build('/posts/:id/comments') | |
m = rx.match('/posts/123/comments') | |
puts m[:id] # 123 | |
m = rx.match('/posts/123/comments.html') | |
puts m[:id] # 123 | |
puts m[:format] # .html |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment