-4

Symbols are immutable objects, are lightweight strings, and are not garbage-collectable. I don't understand how they work in a Rails route or path. For instance, in:

get '/patients/:id', to: 'patients#show'

:id will be replaced by a number, and we get something like /patitent/1. However :id = 1 is not allowed. How is this assignment performed?

6
  • 6
    I believe it's not a symbol, merely a part of a route string, which Rails parses to find an indentifier. Commented Jul 9, 2015 at 11:21
  • I don't understand your logic. '/patients/:id' becoming '/patitent/1' does not mean that :id = 1. 'abc'.gsub(/./, 'x') # => 'xxx' does not mean that a = b = c = 'x'. Commented Jul 9, 2015 at 11:31
  • I don't understand the relevance of immutability, being lightweight strings, or being garbage-collectable to your question. Commented Jul 9, 2015 at 11:34
  • Your claim that symbols are not garbage-collectable is wrong as of now. Commented Jul 9, 2015 at 11:34
  • 1
    @sawa I'd say you're being pretty rude, cut the newbie some slack will you? Commented Jul 9, 2015 at 11:50

1 Answer 1

1

The value '/patients/:id' is a normal Ruby string, and although the :id part looks like a symbol, it is not.

When Rails parses the string, it uses the colon to identify a parameter name in the path. When it sets the parameter from receiveing a request like GET /patients/1, it does not attempt to alter the symbol value, but does something like the following

params[:id] = '1'

Note I'm not 100% certain that is doesn't just use the string "id" as the key here. But either way you can see it does not alter any symbol value, but just uses the name of the symbol so you know which key it will be stored under in the params Hash

The similarity between ':id' as part of the URL parameter definition and for when you use the Symbol literal :id might be confusing, but is a design choice shared used in Rack path handling engine so most Ruby web frameworks use the same style.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.