14

Apart from making it sightly more concise for defining hashes with symbols as keys, are there any other benefits of writing a hash as:

{key1: "value1", key2: "value2"} instead of {:key1 => "value1", :key2 => "value2"}?

Also, what is the convention when you have a mix of strings and symbols as hash keys?

Do you write it as {"key1" => "value1", key2: "value2"} or keep the style consistant as {"key1" => "value1", :key => "value2"}

zsquare
  • 9,916
  • 6
  • 53
  • 87
  • possible duplicate of [Is it a bad style of using key: value instead of :key => value in a hash of Ruby 1.9](http://stackoverflow.com/questions/10631609/is-it-a-bad-style-of-using-key-value-instead-of-key-value-in-a-hash-of-ruby) – the Tin Man Jul 10 '12 at 19:05
  • 1
    When using a mix of strings and symbols as keys, you should consider using [HashWithIndifferentAccess](http://api.rubyonrails.org/classes/ActiveSupport/HashWithIndifferentAccess.html) – Christoph Petschnig Jul 12 '12 at 10:11

2 Answers2

12

It just looks nicer--it's syntactic sugar; it ends up being the same thing.

When mixing keys (ew, why would you do that?) I use the old hash-rocket syntax for the entire hash.

With symbol values I also use the old hash-rocket syntax for the entire hash–this looks icky:

{ ohai: :kthxbye }

I don't like mixing the two styles in the same hash–I think it's confusing.

This is all based on personal preference, though.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
3

It's shorter, and similar to JavaScript notation. Not worth to migrate old notation to the new for any reason, but otherwise choose which you like.

Always keep the code consistent, don't mix notations. It's more readable that way.

Matzi
  • 13,770
  • 4
  • 33
  • 50
  • Actually it is similar to *JavaScript* notation, [*JSON*](http://json.org) requires the keys to be quoted as the keys are explicitly defined to be strings. – mu is too short Aug 29 '14 at 16:12