Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between prepend and append of colon ( :item vs item:)

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?

like image 895
Automatico Avatar asked Aug 13 '13 18:08

Automatico


1 Answers

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.

like image 60
akatakritos Avatar answered Sep 20 '22 17:09

akatakritos