Question

What is the difference between appending and prepending a colon in ruby?

Example:

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

Why does dependent: have an appended colon, but :models and :destroy have a prepended colon? What is the difference?

Was it helpful?

Solution

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.

OTHER TIPS

Since Ruby allows you to omit parenthesis ()and in some cases curly braces {} it might not be very obvious but the above code is actually looking like this:

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

Now, it means that has_many takes two arguments, one being a symbol :, an immutable string if you will, and also a hash where the dependent is the key and destroy is the value; also maybe seen as :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

The "appended" colon is simply the new common way of displaying hashes in 1.9.

dependent: :destroy is the same thing as :dependent => :destroy

On the other hand, a "prepended" colon indicates a symbol data type in Ruby.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top