2013-10-04 75 views
-2

我如何检索我正在查看的特定符号的值?如何访问散列值?

如果我定义在哈希较早这样

:red => "blue" 

我可以调用什么方法的符号:红得到“蓝”? .to_s和.id2name给我 “红”

+0

Ruby的文档相当不错,访问键和值是覆盖在引进了['Hash'](http://ruby-doc.org/core-2.0/Hash.html)。 – Stefan

+0

谢谢,因为我试图在散列之外定义的数组中访问它,我忽略了作为解决方案的简单答案。 – JonnyPolo

回答

2

使用Hash#[]

>> h = {:red => "blue"} 
=> {:red=>"blue"} 
>> h[:red] 
=> "blue" 
0

您可以使用Hash#fetch

h = {:red => "blue"} 
h.fetch(:red) # => "blue"