What is the difference between this: and: this?

advertisements

This question already has an answer here:

  • Is there any difference between the `:key => “value”` and `key: “value”` hash notations? 5 answers

What does the colon denote when used at the beginning and at the end of something? I think that a colon at the begging of something (e.g. :set_cart) denotes a method. Is this correct? Here are a few examples:

<%= button_to "Checkout", new_order_path, method: :get %>
<%= button_to "Empty Cart", @cart, method: :delete,
    data: {confirm: 'Are you sure?' } %>

Edit: Another Example

before_action :set_cart, only: [:new, :create]
before_action :set_order, only: [:show, :edit, :update, :destroy]


A colon at the beginning of something denotes a Ruby Symbol object.

> :name.class
=> Symbol

A colon at the end of something denotes a Symbol key in a Ruby Hash object. This new Hash syntax was introduced in Ruby 1.9.

> hash = { key: 'val' }
=> {:key=>"val"}

When they are used together, as expected, it creates a hash pair with a key and value that are symbols.

> { key: :val }
=> {:key => :val}