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

Ruby实现按指定键过滤新增数组元素去重功能的实现咨询

实现方案

核心思路

  • 在类中新增实例变量@dedup_key,用于存储idefine方法传入的去重依据键名
  • 改写items方法的去重逻辑,优先按@dedup_key指定的键值去重,未配置时走默认的对象相等去重规则
  • 调整新增元素筛选逻辑,保证返回的arrfinish也符合指定的去重规则

完整实现代码

def initialize
  @arr = []
  @dedup_key = nil # 新增去重键存储变量
end

def items(init)
  # 筛选符合规则的新增元素
  arrfinish = if @dedup_key
                # 先提取已存数据的去重键值
                existing_keys = @arr.map { |item| item[@dedup_key] }
                # 先对传入数组按规则去重,再排除已存在的元素
                init.uniq { |i| i[@dedup_key] }.reject { |i| existing_keys.include?(i[@dedup_key]) }
              else
                init - @arr
              end

  # 合并数组并按规则去重
  @arr = if @dedup_key
           (@arr + init).uniq { |item| item[@dedup_key] }
         else
           (@arr + init).uniq
         end

  yield arrfinish if block_given? # 兼容无块调用的场景,避免报错
end

def idefine(find_text)
  @dedup_key = find_text.to_s # 统一转字符串,避免传入Symbol类型导致匹配失败
end

效果验证

使用你给出的示例调用测试:

app_handler = YourClassName.new # 替换为实际的类名
app_handler.idefine('id')
app_handler.items([{'id' => 1}, {'id' => 1, 'test_key' => 'Some data'}, {'id' => 2}]) do |new_items|
  puts new_items # 输出仅为 [{"id"=>1}, {"id"=>2}],第二个id为1的元素被过滤
end
# 最终@arr存储的值为 [{"id"=>1}, {"id"=>2}]

内容的提问来源于stack exchange,提问作者James Bond

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 23:15:03