0

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]
drewwyatt
  • 5,989
  • 15
  • 60
  • 106
  • This is a symbol, if you want to know more there are plenty of resources about this on the internet but you can check that post for instance: http://www.robertsosinski.com/2009/01/11/the-difference-between-ruby-symbols-and-strings/ : ) – Raindal Aug 07 '13 at 18:46
  • @Sparda "This is a symbol" is not very helpful if you don't specify you're referring to `:this` rather than `this:`. – Andrew Grimm Aug 07 '13 at 23:05
  • @AndrewGrimm well as far as I know, without the subtleties of Hashes and stuff, they are both symbols... – Raindal Aug 08 '13 at 15:06

2 Answers2

4

This is the new syntax for symbol-indexed hashes, introduced (I believe) in Ruby 1.9.

Instead of the old { :key => 'value' } you can now write { key: 'value' }. Under the hood the hash is exactly the same, so it's only really a notation change.

2.0.0p247 :001 > { key: 'value' }
 => {:key=>"value"}

In your example, method: :delete is just a different way of writing :method => :delete.

shulima
  • 59
  • 4
  • 1
    In addition, the OP's example code makes use of method-calling convention whereby hash key/value syntax found at the end of a method call is rolled up into a single `Hash` param. – Neil Slater Aug 07 '13 at 18:46
3

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}
cmpolis
  • 3,051
  • 21
  • 19