在 ruby 中附加和附加冒号有什么区别?
例子:
#In rails you often have things like this:
has_many :models, dependent: :destroy
为什么dependent:
有一个附加的冒号,但是有一个附加:models
的:destroy
冒号?有什么区别?
在 ruby 中附加和附加冒号有什么区别?
例子:
#In rails you often have things like this:
has_many :models, dependent: :destroy
为什么dependent:
有一个附加的冒号,但是有一个附加:models
的:destroy
冒号?有什么区别?
This is a new syntax in Ruby 1.9 for defining symbols that are the keys in a hash.
Both prepended and appended :
's define a symbol
, but the latter is only valid during the initialization of a hash.
You can think of a symbol as a lightweight string constant.
It is equivalent to
:dependent => :destroy
Prior to 1.9, hashes were defined with a syntax that is slightly more verbose and awkward to type:
hash = {
:key => "value",
:another_key => 4
}
They simplified it in 1.9:
hash = {
key: "value",
another_key: 4
}
If you are ever writing a module you want to use on Ruby prior to 1.9, make sure you use the older syntax.
由于 Ruby 允许您省略括号()
,并且在某些情况下花括号{}
可能不是很明显,但上面的代码实际上看起来像这样:
has_many(:models, { dependent: :destroy } )
现在,这意味着它has_many
需要两个参数,一个是 symbol :
,一个不可变的字符串,如果你愿意,还有一个 hash ,其中dependent
keydestroy
是 value;也可能被视为:dependent => destroy
.
In both cases the colon indicates a symbol, but appending it is shorthand for when the symbol is a key in a hash.
dependent: :destroy
is the same as
:dependent => :destroy
“附加”冒号只是 1.9 中显示哈希的新常用方式。
dependent: :destroy
是一样的:dependent => :destroy
另一方面,“前置”冒号表示 Ruby 中的符号数据类型。