43

What's the difference between colon : and fat arrow => in Ruby? Or when to use what?

:foo => true
foo: true
mu is too short
  • 426,620
  • 70
  • 833
  • 800
John Base
  • 457
  • 1
  • 4
  • 6

2 Answers2

35

The syntax is for defining Hash key/value pairs, and the difference depends on the Ruby version.

Supported in both Ruby 1.8 and Ruby 1.9

:foo => true

Supported only in Ruby 1.9

foo: true

If you're developing in Ruby 1.9 you should probably use the syntax:

foo: true

as it appears to be the direction the community is moving in.

Francesco
  • 3,200
  • 1
  • 34
  • 46
JDutil
  • 3,622
  • 25
  • 32
  • 3
    Where did you hear that `=>` would be deprecated? – Andrew Grimm Nov 20 '11 at 07:09
  • 1
    Yeah, where did you hear `=>` is going to be deprecated? I don't recall such a thing. And even if it were true, it would break the main Hash functionality that any object can serve as the key. So, only symbols could be used as keys if that happened! eg: `{Object => Object}` would no longer exist [that was pseudo code of a sort]. – omninonsense Nov 20 '11 at 16:24
  • Sorry I can't recall where I heard that I may have made it up. I've removed the reference to it eventually being deprecated. – JDutil Nov 21 '11 at 23:03
  • You may have heard that `=>` is obsolete from http://peepcode.com/blog/2011/rip-ruby-hash-rocket-syntax – Andrew Grimm Apr 04 '12 at 03:26
  • @AndrewGrimm: That blog post is overly dramatic nonsense. Blarg. Don't worry, I know you know that already :) – mu is too short Apr 24 '12 at 06:11
10

The latter is the new Hash syntax introduced in 1.9. See, for example:

http://breakthebit.org/post/8453341914/ruby-1-9-and-the-new-hash-syntax

The hashes that the two lines generate are identical.

Ryan H.
  • 7,374
  • 4
  • 39
  • 46
Alex Peattie
  • 26,633
  • 5
  • 50
  • 52
  • 6
    This is only for when the key is a symbol. If you want another object for the key, you'll need the fat arrow as before. – Joe Flynn Mar 12 '13 at 13:26
  • 4
    On that point, note that `{"key": "value"}` will be silently converted to `{:key=>"value"}` - the string will be turned into a symbol. If you want a string key, use `{"key"=>"value"}`. – Sam Apr 06 '20 at 08:59