0

Possible Duplicate:
Is there any difference between the :key => “value” and key: “value” hash notations?

What's the difference between this:

method: :delete

and this?

:method => :delete

I'm guessing it has to do with different versions of Rails but not sure. I have only worked in Rails 3.x.

Community
  • 1
  • 1
botbot
  • 7,299
  • 14
  • 58
  • 96
  • well i sorta inferred that much but curious why have two different ways...? one seems like a json-like 'method: :delete and :method => :delete seems more railsy. have both of these syntaxes been available across all rails versions? – botbot Aug 05 '12 at 20:15
  • 3
    Doesn't have to do a lot with Rails. It's plain Ruby. The hash-rocket notation is there since ever. The colon syntax was introduced with Ruby 1.9. – iltempo Aug 05 '12 at 20:17
  • @kurtybot sorry, I didn't realize you had already inferred that – Abram Aug 05 '12 at 20:19
  • See also http://stackoverflow.com/questions/4563766/hash-syntax-in-ruby http://stackoverflow.com/questions/8220195/allowing-for-ruby-1-9s-hash-syntax http://stackoverflow.com/questions/11412242/what-are-the-benefits-of-the-new-hash-syntax-in-ruby-1-9 http://logicalfriday.com/2011/06/20/i-dont-like-the-ruby-1-9-hash-syntax/ – knut Aug 05 '12 at 20:23
  • +1 @Abram. Andrew Marshall, i had a feeling it would be a duplicate thread but it's not a super search friendly topic. – botbot Aug 05 '12 at 20:47

1 Answers1

0

They are completely equivalent, except the first can only be used since ruby 1.9 (and higher, of course).

In ruby 1.8 the hash syntax used the =>, also known as the hash rocket. You could put anything in front, and anything behind, but the thing in front is your key, behind the value. If you have a symbol as key, and a symbol as value, you would write:

:method => :delete

But you could also write

{ 1 => 'one', :2 => 'two', 'THREE' => 3 }

Now, for ruby 1.9.x, a new shorter syntax was introduced. Since most people use symbols as keys, you can now write:

method: :delete

Which is just a shorter/cleaner version. Also note that it is possible to mix both styles, which in some cases is needed.

E.g. in ruby 1.8 you would write:

{ :class => 'smthg', :'data-type' => 'a type' }

This would translate to the following in ruby 1.9

{ class: 'smthg', :'data-type' => 'a type' }

Note that you can still keep using the "old" hash syntax as well. It is a matter of preference. Personally for hashes with only symbols as keys, I use the clean/short version. I generally try not to mix hash-style in a single hash :)

nathanvda
  • 49,707
  • 13
  • 117
  • 139