[英]Should I use quotes or colons for session keys in Ruby on Rails?
Currently I have a session variable that returns the same value when I use both session["test"]
or session[:test]
. 目前我有一个会话变量,当我使用session["test"]
或session[:test]
时返回相同的值。 Are these two the same? 这两个是一样的吗? Is it better to use one over the other? 使用一个比另一个更好吗?
Thanks 谢谢
In a standard Ruby Hash they're not the same ( string vs symbol ) 在标准的Ruby Hash中,它们不一样( 字符串与符号 )
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): 但是,rails SessionHash
子类在存储它们之前会对键调用to_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's why session[:test]
and session["test"]
will return the same value in rails. 这就是session[:test]
和session["test"]
将在rails中返回相同值的原因。
As far as ruby string and symbols go they are not the same. 就红宝石串和符号而言,它们并不相同。
As a general rule, you should use the second form, a symbol is something used to represent something which would otherwise be a string. 作为一般规则,您应该使用第二种形式,符号是用于表示本来是字符串的东西的东西。 It is a way to efficiently have descriptive names while saving the space you would use to generate a string multiple times. 这是一种有效地具有描述性名称的方法,同时节省了用于多次生成字符串的空间。
This means that you do not create a new instance each time you refer to the symbol as you would a string. 这意味着每次引用符号时都不会像创建字符串那样创建新实例。 The symbol is simply a better way to represent the value you are describing. 符号只是表示您所描述的值的更好方式。
Just for completeness, I should mention a symbol can trivially be converted to a string if you need a representation later. 为了完整起见,我应该提一下,如果以后需要表示,可以将符号简单地转换为字符串。
if you want to read more there is a lengthy blog post just here which explains ruby symbols well. 如果您想了解更多有一个漫长的博客帖子就在这里这也解释了红宝石象征好。 Suffice to say they are an optimisation. 可以说它们是一种优化。
That said ruby SessionHash calls to_s on symbols so you can use either in this case as a string will result from the input either way. 那就是说ruby SessionHash在符号上调用to_s,所以你可以在这种情况下使用任何一种方式作为字符串。
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. 通常,在Ruby中,符号的主要用途是键。 Symbols are :these_things
. 符号是: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. 使用字符串不会伤害任何东西,但符号更典型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.