ardochhigh ardochhigh - 7 months ago 13
Ruby Question

How to extract a route params using Ruby

I have some strings that look like any of these:

/challenges/:challenge_id/submissions/:id
/challenges/:challenge_id/submissions
/api/v1/submissions/:id
/submissions


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

/[:[a-z*]]/


I'm testing in http://rubular.com/ as I need this to run in Ruby code.

Answer
arr = []
"/challenges/:challenge_id/submissions/:id".gsub(/:[^\/]+/){|s| arr.push(s); "1"}
# => "/challenges/1/submissions/1"
arr
# => [":challenge_id", ":id"]
Comments