Hash syntax in Ruby [duplicate]

这一生的挚爱 提交于 2020-01-09 10:36:11

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/4563766/hash-syntax-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!