Reputation: 213
I would like to get some data from a URL in Ruby. I have a URL matching:
"http://localhost:3000/cars/test/1/direction/2"
I would like to extract the value after /test
(here it is 1
). I know how to extract the other values.
I created a URI object:
uri = URI.parse("http://localhost:3000/cars/test/1/direction/2")
uri.port = 3000
uri.path = /cars/test/1/direction/2
uri.host = localhost
But, I don't know how to extract the internal parameters.
Do I have to parse this URL or is there an existing solution?
Upvotes: 0
Views: 212
Reputation: 16677
The quick and easy solution is to just use split
.
uri = URI.parse("http://localhost:3000/cars/test/1/direction/2")
url_path = uri.path
url_parts = url_path.split("/")
url_parts[3] # => "1"
Upvotes: 0
Reputation: 29318
I think this might work well for you as it identifies the leading name as well:
url_parts = uri.path.scan(/\/(\w+)\/(\d+)/)
#=> [["test","1"],["direction","2"]]
Then you could even make it a Hash
using:
Hash[url_parts]
#=> {"test" => "1", "direction" => "2"}
Upvotes: 2