Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby Building Web Apps with Sinatra ERB Templates URL Parameters

tarioug MA
tarioug MA
4,489 Points

Why get("/:title") did store the title of the page in the symbol title ?

Hi everybody,

I'm really confused about this line :

get "/:title" do...

How is it possible for sinatra to recognize that the string put in the url has to be stored in :title ?

I hope my question is clear.

Thank's a lot

Tarioug

3 Answers

Jose Soto
Jose Soto
23,407 Points
get "/:title" do
    params[:title]
end

The above code is another way of saying, "when you go to the url /something, the string something, will be available in the variable params[:title]. In the above case, it will simply display the string when you hit that route. It's similar to using GET request parameters like localhost/?title=something.

tarioug MA
tarioug MA
4,489 Points

Thank you for your response Jose.

But why I can't write this :

          get "/title" do
    params[title]
end
Jose Soto
Jose Soto
23,407 Points

That route will only be called when you visit the url localhost/title. For example, if you only have that route and you go to localhost/foobar, Sinatra will error out because you do not have a route for get "/foobar".

Adding the colon before title tells Sinatra that whatever the user enters for that route will be placed into a variable for use in your program.

I think because params is a hash and the ":title" is a symbol, so when returning "params[:title]" you're returning the params hash symbol value

tarioug MA
tarioug MA
4,489 Points

Ok it's clear. Thank you Jose