Ruby中的哈希语法 [英] Hash syntax in Ruby
问题描述
Ruby允许在散列键位置使用特殊形式的符号表示形式,冒号之后的符号,而不是之前和散列分隔符箭头删除。换句话说,这是:
hash = {:name => David,:age => 49}
也可以这样写:
hash = {姓名:David,年龄:49}
我已经在ruby 1.8.7和1.9.2中试过了上面的代码 - 它不工作。我在做什么错了?
Ruby 1.9中的新哈希语法仍然要求引用字符串, c $ c> David 您需要
David
。 试试这个:
hash = {name:David,age:49}
如果本书使用不带引号的单词 David
,这是错误的。您可能有兴趣阅读一些其他勘误。
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.
这篇关于Ruby中的哈希语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!