1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Sinatra URL Matching


Named parameters are portions of the URL that will act as a parameter. For example, /hello/:name will match any URL that looks like /hello/alice or /hello/bob. In the request handler, the contents of the :name portion of the request URL will be available as params[:name].

Named parameters match any character up to the next slash. While they're usually used for just single word parameters, or perhaps parameters with a number of words separated by dashes, they can be used for more complex parameters. Though regular expressions may be more appropriate than named parameters in that case.

#!/usr/bin/env ruby
require 'rubygems'
require 'sinatra'

get '/hello/:name' do
  "Hello #{params[:name]}"

get '/tell/:name/:greeting' do
  "#{params[:greeting]} #{params[:name]}"
# This handler will never match, as the first
# handler hides it
get '/hello/bob' do
  "Hi there Bob!!"

# This handler is OK though, since the first
# handler must have a second part after the
# slash
get '/hello' do

Here, the /hello/:name handler is something we've seen before. The handler is quite straight forward, it will take any string passed in the :name parameter section and add it to the response.

The second /tell/:name/:greeting handler is a little more complex. Here, the :name parameter will match any string of characters without a slash in it. This includes spaces and other symbols. So you can make a request to /tell/Alice and Bob/Hi there and everything will go as expected.

  1. About.com
  2. Technology
  3. Ruby
  4. Tutorials
  5. Sinatra
  6. Named Parameters

©2014 About.com. All rights reserved.