Ruby解析数据库表并按类型存为Hash及查询ID对应类型的方法
JSON数据筛选、Hash构建及ID查询实现
一、数据筛选与目标Hash构建
首先处理JSON数据,筛选出type为Atest或Btest的条目,并构建符合编程语言逻辑的Hash结构(注:原示例中的Hash存在重复key问题,实际编程中不允许重复key,以下提供两种合理实现方案)。
方案1:按type分组存储
将同类型的条目归到同一key下,value为包含id和description的Hash数组:
require 'json' # 原始JSON数据 json_data = <<~JSON [ {"id": 1 , "type": "Atest", "ip":"10.2.0.1", "port":1234, "description": "xyz"}, {"id": 2 , "type": "Btest", "ip":"10.2.0.2", "port":3000, "description": "xyz"}, {"id": 3 , "type": "subtest", "ip":"10.2.0.3", "port":3001, "description": "xyz"}, {"id": 4 , "type": "Atest", "ip":"10.2.0.4", "port":9999, "description": "xyz"}, {"id": 5 , "type": "subtest", "ip":"10.2.0.5", "port":1235, "description": "xyz"}, {"id": 6 , "type": "Ctest", "ip":"10.2.0.6", "port":1111, "description": "xyz"}, {"id": 7 , "type": "Btest", "ip":"10.2.0.7", "port":2222, "description": "xyz"}, {"id": 8 , "type": "subtest", "ip":"10.2.0.8", "port":3333, "description": "xyz"} ] JSON # 解析JSON为Ruby数组 data_array = JSON.parse(json_data) # 筛选目标类型并构建分组Hash target_types = ["Atest", "Btest"] grouped_hash = data_array.each_with_object(Hash.new { |h, k| h[k] = [] }) do |item, hash| if target_types.include?(item["type"]) hash[item["type"]] << { id: item["id"], description: item["description"] } end end # 输出结果示例 # {"Atest"=>[{:id=>1, :description=>"xyz"}, {:id=>4, :description=>"xyz"}], "Btest"=>[{:id=>2, :description=>"xyz"}, {:id=>7, :description=>"xyz"}]}
方案2:以id为key存储(便于后续查询)
将每个条目的id作为Hash的key,value包含type和description:
# 筛选目标类型并构建id为key的Hash id_based_hash = data_array.each_with_object({}) do |item, hash| if target_types.include?(item["type"]) hash[item["id"]] = { type: item["type"], description: item["description"] } end end # 输出结果示例 # {1=>{:type=>"Atest", :description=>"xyz"}, 2=>{:type=>"Btest", :description=>"xyz"}, 4=>{:type=>"Atest", :description=>"xyz"}, 7=>{:type=>"Btest", :description=>"xyz"}}
二、按特定ID查询对应类型
基于方案2的快速查询
利用id为key的Hash,可直接通过id快速获取类型:
# 定义查询方法 def get_type_by_id(hash, target_id) entry = hash[target_id] entry ? entry[:type] : "未找到对应ID的条目" end # 示例查询 puts get_type_by_id(id_based_hash, 1) # 输出:Atest puts get_type_by_id(id_based_hash, 7) # 输出:Btest puts get_type_by_id(id_based_hash, 3) # 输出:未找到对应ID的条目
基于方案1的遍历查询
如果使用分组Hash,可通过遍历实现查询:
def get_type_by_id_from_grouped(hash, target_id) hash.each do |type, entries| entries.each do |entry| return type if entry[:id] == target_id end end "未找到对应ID的条目" end # 示例查询 puts get_type_by_id_from_grouped(grouped_hash, 4) # 输出:Atest
内容的提问来源于stack exchange,提问作者Rubin
相关产品推荐
相关产品推荐

