Ruby 中的哈希语法 [英] Hash syntax in Ruby

查看:24
本文介绍了Ruby 中的哈希语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据扎实的Rubyist:

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

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 }

也可以这样写:

hash = { name: David, age: 49 }

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

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

推荐答案

Ruby 1.9 中的新散列语法仍然要求字符串被引用,因此您需要 "David" 而不是 David.

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

试试这个:

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

如果书中使用了没有引号的裸词David,那是错误的.您可能有兴趣阅读一些其他勘误.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆