Don*_*son 1 ruby hash ruby-on-rails
我正在尝试处理哈希中不一致的键(字符串/符号)。我认为 HashWithIndifferentAccess 将是答案,但在尝试对这些散列进行一些基本操作时,我得到了一些稍微令人困惑的结果
例如我有以下 HashWithIndifferentAccess
(rdb:1) metadata
{"indexes"=>["respondent", "brand"], "columns"=>["rating"],
"value_labels"=>{}, "column_labels"=>{}}
(rdb:1) metadata.class
ActiveSupport::HashWithIndifferentAccess
Run Code Online (Sandbox Code Playgroud)
当我尝试以下选择时,我得到一个空哈希
(rdb:1) metadata.select{ |k, v| [:indexes, :columns, :value_labels, :column_labels]
.include? k }
{}
Run Code Online (Sandbox Code Playgroud)
HashWithIndifferentAccess 是否可以使用所有常见的哈希操作?为什么此操作返回空哈希
您真正获得的HashWithIndifferentAccess只是使用字符串或键设置和获取值的能力。一旦你开始在散列上使用其他读取方法,你就会移动到不是对字符串或符号感兴趣的。
但是,HashWithIndifferentAccess 确实可以帮助您,因为:
在整个编写界面(调用 []=、merge 等)中用作键时,内部符号会映射到字符串
....
您可以保证密钥作为字符串返回
这意味着您总是会使用以下方法获取键的字符串select:
> h = { sym_key: 'sym_value', 'string_key' => 'string_value' }.with_indifferent_access
> h.keys
=> ["sym_key", "string_key"]
Run Code Online (Sandbox Code Playgroud)