开发者

Hash syntax in Ruby [duplicate]

This question already has answers here: Is there any difference between the开发者_如何学Python `:key => "value"` and `key: "value"` hash notations? (5 answers) Closed 5 years ago.

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜