【问题标题】:Select on hash with indifferent access not working在具有无关访问权限的哈希上选择不起作用
【发布时间】:2015-10-16 10:11:55
【问题描述】:

我正在尝试处理哈希中不一致的键(字符串/符号)。我认为 HashWithIndifferentAccess 将是答案,但在尝试对这些哈希进行一些基本操作时,我得到了一些稍微令人困惑的结果

例如我有以下 HashWithIndifferentAccess

(rdb:1) metadata
{"indexes"=>["respondent", "brand"], "columns"=>["rating"], 
 "value_labels"=>{}, "column_labels"=>{}}
(rdb:1) metadata.class
ActiveSupport::HashWithIndifferentAccess

当我尝试以下选择时,我得到一个空哈希

(rdb:1) metadata.select{ |k, v| [:indexes, :columns, :value_labels, :column_labels]
.include? k }
 {}

HashWithIndifferentAccess 是否可以使用所有常见的哈希运算?为什么这个操作返回一个空哈希

【问题讨论】:

    标签: ruby-on-rails ruby hash


    【解决方案1】:

    您真正使用HashWithIndifferentAccess 获得的只是使用字符串或键设置和获取值的能力。一旦你开始在哈希上使用其他读取方法,你就会移动到不是对字符串或符号无动于衷的对象。

    但是,HashWithIndifferentAccess确实可以帮助您,因为:

    在整个书写界面中用作键时(调用[]=、合并等),内部符号被映射到字符串

    ....

    您可以保证密钥作为字符串返回

    这意味着您将始终使用select 之类的方法获取键的字符串:

    > h = { sym_key: 'sym_value', 'string_key' => 'string_value' }.with_indifferent_access
    > h.keys
    => ["sym_key", "string_key"]
    

    【讨论】:

      【解决方案2】:

      无差别访问意味着HashWithIndifferentAccess#[] 将检查字符串和键。但是,Array#include? 上没有这样的补丁,您正在使用它来过滤您的数据。轻松修复:

      [:indexes, :columns, :value_labels, :column_labels].include? k.to_sym
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-08-18
        • 1970-01-01
        • 1970-01-01
        • 2016-01-26
        • 2015-05-24
        • 2014-05-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多