7

在 ruby​​ 中附加和附加冒号有什么区别?

例子:

#In rails you often have things like this:
has_many :models, dependent: :destroy

为什么dependent:有一个附加的冒号,但是有一个附加:models:destroy冒号?有什么区别?

4

4 回答 4

10

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.

于 2013-08-13T19:04:29.140 回答
5

由于 Ruby 允许您省略括号(),并且在某些情况下花括号{}可能不是很明显,但上面的代码实际上看起来像这样:

has_many(:models, { dependent: :destroy } )

现在,这意味着它has_many需要两个参数,一个是 symbol :,一个不可变的字符串,如果你愿意,还有一个 hash ,其中dependentkeydestroy是 value;也可能被视为:dependent => destroy.

于 2013-08-13T19:07:22.497 回答
4

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
于 2013-08-13T19:04:11.763 回答
2

“附加”冒号只是 1.9 中显示哈希的新常用方式。

dependent: :destroy是一样的:dependent => :destroy

另一方面,“前置”冒号表示 Ruby 中的符号数据类型。

于 2013-08-13T19:07:18.950 回答