-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?

sawa
  • 165,429
  • 45
  • 277
  • 381
Fran b
  • 3,016
  • 6
  • 38
  • 65
  • 6
    I believe it's not a symbol, merely a part of a route string, which Rails parses to find an indentifier. – Piotr Kruczek Jul 09 '15 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'`. – sawa Jul 09 '15 at 11:31
  • I don't understand the relevance of immutability, being lightweight strings, or being garbage-collectable to your question. – sawa Jul 09 '15 at 11:34
  • Your claim that symbols are not garbage-collectable is wrong as of now. – sawa Jul 09 '15 at 11:34
  • 1
    @sawa I'd say you're being pretty rude, cut the newbie some slack will you? – Jesper Jul 09 '15 at 11:50
  • Thank you for yor patience @sawa. The reference about garbage-collectable comes from here: http://stackoverflow.com/questions/11447537/using-ruby-symbols I'm learning ruby, so I confused a symbol with a variable. – Fran b Jul 09 '15 at 12:06

1 Answers1

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.

Neil Slater
  • 26,512
  • 6
  • 76
  • 94