You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby中如何基于自定义结构过滤服务返回的哈希数组并保留指定字段

Ruby自定义结构类过滤哈希字段方案

实现思路

通过自定义类明确声明需要保留的字段列表,初始化时自动过滤原始哈希的多余字段,同时支持导出为标准哈希格式适配后续业务逻辑。

代码实现

1. 自定义结构类定义

class DiagnosisItem
  # 声明需要保留的字段
  REQUIRED_FIELDS = %w[
    alias
    code
    code_system_id
    diagnosis_code
    diagnosis_code_description
    last_service_date
    status
  ].freeze

  attr_accessor(*REQUIRED_FIELDS)

  def initialize(raw_hash)
    REQUIRED_FIELDS.each do |field|
      public_send("#{field}=", raw_hash[field]) if raw_hash.key?(field)
    end
  end

  # 导出为符合要求的哈希
  def to_h
    REQUIRED_FIELDS.each_with_object({}) do |field, res|
      res[field] = public_send(field)
    end
  end
end

2. 调用方法

# 原始响应哈希
h = { "data"=>
  [
    { 
      "alias"=>"abc",
      "code"=>"fgh",
      "code_system_id"=>"1234",
      "diagnosis_code"=>"5678",
      "diagnosis_code_description"=>"Test",
      "last_service_date"=>"2021-02-17T18:00:00.000Z",
      "status"=>"PENDING",
      "pastPeriodSupportingData"=>[],
      "currentPeriodSupportingData"=>[
        {
          "conditionId"=>"1212",
          "effectiveDate"=>"2021-02-17T18:00:00.000Z"
        }
      ],
      "suppressed"=>false
    },
    {
      "alias"=>"abcde",
      "code"=>"klm jh",
      "code_system_id"=>"65656",
      "diagnosis_code"=>"21321",
      "diagnosis_code_description"=>"somesom",
      "last_service_date"=>"2021-02-17T18:00:00.000Z",
      "status"=>"PENDING",
      "pastPeriodSupportingData"=>[],
      "currentPeriodSupportingData"=>[
        {
          "conditionId"=>"1234efgh1",
          "effectiveDate"=>"2021-02-17T18:00:00.000Z"
        }
      ],
      "suppressed"=>false
    }
  ]
}

# 转换得到目标结果
target_result = {
  "data" => h["data"].map { |raw| DiagnosisItem.new(raw).to_h }
}

轻量化替代方案

如果不需要扩展逻辑,仅需要一次性过滤,可直接使用Ruby Hash原生的slice方法实现,无需定义类:

allowed_fields = %w[alias code code_system_id diagnosis_code diagnosis_code_description last_service_date status]
target_result = { "data" => h["data"].map { |item| item.slice(*allowed_fields) } }

内容的提问来源于stack exchange,提问作者supreet singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 02:45:04