Currently I have a session variable that returns the same value when I use both session["test"]
or session[:test]
. Are these two the same? Is it better to use one over the other?
Thanks
Ruby symbols are created by placing a colon (:) before a word. You can think of it as an immutable string. A symbol is an instance of Symbol class, and for any given name of symbol there is only one Symbol object.
Learn what a colon before a variable means in Ruby This means that two symbols with the same name always refer to the same object.
Rails session is only available in controller or view and can use different storage mechanisms. It is a place to store data from first request that can be read from later requests. Following are some storage mechanism for sessions in Rails: ActionDispatch::Session::CookieStore - Stores everything on the client.
In a standard Ruby Hash they're not the same (string vs symbol)
However, the rails SessionHash
subclass calls to_s
on the keys before storing them, so all keys are stored as strings (even if you specify a symbol):
class SessionHash < Hash
def [](key)
load_for_read!
super(key.to_s)
end
def []=(key, value)
load_for_write!
super(key.to_s, value)
end
That's why session[:test]
and session["test"]
will return the same value in rails.
No, they aren't precisely the same. They're two ways of accomplishing the same thing.
In general, in Ruby a major use of symbols is as keys. Symbols are :these_things
. Hash keys are a typical use for them...
{
:name => 'Mary',
:rank => 'Captain'
}
Session keys are also usually symbols.
Using Strings instead won't hurt anything, but symbols are more typical.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With