ardochhigh ardochhigh - 2 years ago 73
Ruby Question

How to extract a route params using Ruby

I have some strings that look like any of these:


The strings starting with ':' and ended by a '/' or a blank line are Rails route params. ie: 'challenge_id' and ':id'

I'd like to do 2 things with this string

  • extract the route param variables into a ruby array for later use

  • replace those param variables by '1'

So output for the first example:

arr = [':challenge_id',':id']
new string = '/challenges/1/submissions/1'

I've tried this, but it is matching everything


I'm testing in as I need this to run in Ruby code.

Answer Source
arr = []
"/challenges/:challenge_id/submissions/:id".gsub(/:[^\/]+/){|s| arr.push(s); "1"}
# => "/challenges/1/submissions/1"
# => [":challenge_id", ":id"]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download