24

According to The Well Grounded Rubyist:

Ruby allows a special form of symbol representation in the hash-key position, with the colon after the symbol instead of before it and the hash separator arrow removed. In other words, this:

hash = { :name => "David", :age => 49 }

can also be written like this:

hash = { name: David, age: 49 }

I have tried the preceding code in ruby 1.8.7 and 1.9.2 - It is not working. What am I doing wrong?

Kevin Sylvestre
  • 37,288
  • 33
  • 152
  • 232
grigoryvp
  • 40,413
  • 64
  • 174
  • 277
  • 9
    In the future, please post detailed error messages if you can't make a code snippet work. This is much more useful than "it's not working". – user229044 Dec 30 '10 at 15:22
  • Thanks, I was trying to know when the `hash`s `json-like` syntax to be used, and it is apparently available only with `symbols`. – Muhammad Hewedy Sep 08 '15 at 08:07

1 Answers1

39

The new hash syntax in Ruby 1.9 still requires that strings be quoted, so instead of David you need "David".

Try this:

hash = { name: "David", age: 49 }

If the book used the bare word David without quotation marks, it is wrong. You might be interested in reading some of the other errata.

user229044
  • 232,980
  • 40
  • 330
  • 338