0

What's the difference between => and : for hash keys in Ruby?

  delegate :sum, to: :CONSTANT_ARRAY


  delegate :sum, :to => :CONSTANT_ARRAY

Why would one be better than another?

user3179047
  • 324
  • 2
  • 12

3 Answers3

4

=> is more general than just :. With => the key can be any data type, whereas using : forces the key to be a symbol.

For example:

{ a: 1 }
# => {:a=>1} # The key is the symbol :a

{ 'a' => 1 }
# => {"a"=>1} # The key is the string "a"

{ "a": 1 }
# => SyntaxError

Why would one be better than another?

If your keys are symbols then you may find the : syntax to be clearer and less cluttered. It is also immediately recognizable to those who are familiar with the JSON data format (though technically the key must be a string surrounded by double-quotes (") according to the standard to be valid JSON syntax, but the non-quoted keys are recognized in many languages including JavaScript.)

Matt
  • 20,108
  • 1
  • 57
  • 70
0

There's no difference.

It depends on your preference.

delegate :sum, to: :CONSTANT_ARRAY is the Ruby 1.9 and after syntax.

delegate :sum, :to => :CONSTANT_ARRAY is the Ruby 1.8 syntax.

Jason Kim
  • 18,102
  • 13
  • 66
  • 105
0

Basically, in this case, there's no difference.

The Hash-Rocket => is the old style, probably borrowed from perl, while the colon syntax is the newer, ruby 1.9 style of writing hashes.

The latter is more directed towards json-notation and therefore might be easier to read if one is more familiar with it.

Karsten S.
  • 2,349
  • 16
  • 32
  • Wrong. `$set: { 'a.b': 'c' }` is a syntax error but `:$set => { :'a.b' => 'c' }` is fine (and fairly common if you work with MongoDB). – mu is too short Mar 04 '14 at 18:57
  • 1
    If you look at the given example in the original post, there is no difference. – Karsten S. Mar 04 '14 at 23:09
  • But to say "there's no difference" is still incorrect, that statement should be qualified at the very least. To refer to them as *new* and *old* styles is also incorrect. Even to say that `a: 'b'` is *json-notation* is incorrect since JSON requires that keys be quoted, referring to it as JavaScript-notation would be more accurate. – mu is too short Mar 04 '14 at 23:14
  • Ok, let me say it differently and edit my post accordingly. – Karsten S. Mar 05 '14 at 10:14