ruby符号作为键,但无法从哈希中获取值

Lor*_*ang 3 ruby hash symbols

我正在对其他人的代码进行一些更新,现在我有一个哈希,就像:

{"instance_id"=>"74563c459c457b2288568ec0a7779f62", "mem_quota"=>536870912, "disk_quota"=>2147483648, "mem_usage"=>59164.0, "cpu_usage"=>0.1, "disk_usage"=>6336512}
Run Code Online (Sandbox Code Playgroud)

我希望按符号获取值作为键,例如:: mem_quota,但失败了.

代码如下:

instance[:mem_usage].to_f
Run Code Online (Sandbox Code Playgroud)

但它什么也没有回报.有什么理由可以导致这个问题吗?

Con*_*ner 10

instance["mem_usage"]改用,因为哈希不使用符号.


Ser*_*sev 5

您需要 HashWithIndifferentAccess。

require 'active_support/core_ext'

h1 = {"instance_id"=>"74563c459c457b2288568ec0a7779f62", "mem_quota"=>536870912, 
  "disk_quota"=>2147483648, "mem_usage"=>59164.0, "cpu_usage"=>0.1, 
  "disk_usage"=>6336512}

h2 = h1.with_indifferent_access

h1[:mem_usage] # => nil
h1["mem_usage"] # => 59164.0

h2[:mem_usage] # => 59164.0
h2["mem_usage"] # => 59164.0
Run Code Online (Sandbox Code Playgroud)


ebe*_*and 5

其他解释是正确的,但提供了更广阔的背景:

您可能已经习惯在Rails中工作,在该Rails中,非常特殊的Hash变体HashWithIndifferentAccess用于诸如params之类的事情。该特殊类的工作方式类似于标准的ruby Hash,但当您访问键时,允许使用符号或字符串。标准的Ruby Hash(通常是其他语言的Hash实现)期望访问元素,用于以后访问的密钥应该是与用于存储该对象的密钥具有相同类和值的对象。HashWithIndifferentAccess是通过Active Support库提供的Rails便利类。您可以自己自由使用它们,但是首先需要提供它们。

HashWithIndifferentAccess只是在访问时从字符串到符号进行转换。

因此,对于您的情况,instance [“ mem_usage”]。to_f应该可以工作。