Should I use quotation marks or colons for session keys in Ruby on Rails?

I currently have a session variable that returns the same value when I use both session["test"], and session[:test]. Are these two the same? Is it better to use one over the other?

thank

+5
source share
3 answers

In standard Ruby Hash, they do not match ( string vs symbol )

However, subclasses are called on keys before storing them, so all keys are stored as strings (even if you specify a character): SessionHashto_s

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 is why session[:test]they session["test"]will return the same value in rails.

+4
source

No, they do not match, this is a string, the other is a character

, - -, , . , , .

, , , . - , .

, , .

, , . , .

0

, . - .

In general, in Ruby, the main use of characters is keys. Symbols :these_things. They are characterized by hash keys ...

{
  :name => 'Mary',
  :rank => 'Captain'
}

Session keys are also usually characters.

Using strings instead will not hurt anything, but characters are more typical.

0
source

All Articles