2

Ruby 1.9.2 的新哈希语法有一个奇怪的问题。如何在 1.9.2 中将任何对象作为哈希键?

在 1.8.7 哈希中它可以工作:

a="b" 
{"a" => "some",a => "another value",:a => "3rd value"}

但是在 1.9.2 > 我们不能(或者如果我错了怎么办?”)

1.9.2 哈希:

{a: "some"} =>  {:a=>"s"} #it convert to old hash format

a="a" 
{a: "..."} # This doesn't work

{"a": "some value"} => syntax error, unexpected '}', expecting $end
from /home/naveed/.rvm/rubies/ruby-1.9.2-p290/bin/irb:16:in `<main>'

{1: "s"} =>

SyntaxError: (irb):11: syntax error, unexpected ':', expecting tASSOC {1: "s"}
4

2 回答 2

6

在 Ruby 1.9 中,您只能在用作键的: 符号之后放置冒号!

任何对象都可以使用箭头=>,甚至符号。

于 2012-04-24T08:00:53.223 回答
3

To say this another way, the new feature isn't a new general hash syntax, it's a specific tweak for writing hashes where the keys are symbol literals. {a: 1} is just a shortcut for {:a => 1}, and that's all. If you have anything else as keys, you have to use the regular syntax.

于 2012-05-15T02:33:12.720 回答