ruby - Ruby 中的哈希语法

标签 ruby hash syntax-error

<分区>

根据 The Well Grounded Rubyist 的说法:

Ruby 允许在散列键位置使用特殊形式的符号表示,冒号位于符号之后而不是之前,并且删除了散列分隔符箭头。换句话说,这:

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

也可以这样写:

hash = { name: David, age: 49 }

我已经在 ruby​​ 1.8.7 和 1.9.2 中尝试了前面的代码 - 它不起作用。我做错了什么?

最佳答案

Ruby 1.9 中新的哈希语法仍然需要引用字符串,因此您需要 "David" 而不是 David

试试这个:

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

如果本书使用了没有引号的裸词David,那是错误的。您可能有兴趣阅读一些 other errata .

关于ruby - Ruby 中的哈希语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4563766/

相关文章:

regex - 为什么破折号会扰乱正则表达式搜索?

python - 如何在sqlite中从此循环插入数据

vb.net - OleDbAdapter错误,在封闭 block 中隐藏变量错误

c# - 为任意一组键(任意数据类型)获取可散列对象的最有效方法

c# - 将代码转换为 C#?

vba - Excel VBA #值(value)!错误

ruby - 轨道 3 : is there way to automatically create a hash from a string representation of a hash

ruby-on-rails - Rails 4 路由带有可选参数?

ios - 设计注册 Controller 拒绝来自 iOS 的 POST

oracle - 在 Oracle 中对一行进行 sha1 哈希