0

我在 test.rb 文件中有以下代码:

hello = { :credit => "Testing" }
acc = ":credit"
puts hello[a.to_sym]

当我将它运行为:ruby test.rb时,我应该得到 Hash 元素(测试)的值,但我什么也没得到。

我究竟做错了什么?提前感谢您的回答。

4

1 回答 1

4

字符串中的冒号是什么让你搞砸了。

1.9.3p429 :003 > acc.to_sym
:":credit"

你需要让它只是“信用”

1.9.3p429 :004 > acc = "credit"
"credit"
1.9.3p429 :005 > acc.to_sym
:credit
1.9.3p429 :006 > hello[acc.to_sym]
"Testing"
于 2013-07-03T14:50:49.843 回答