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

Ruby中如何重写数组减号运算符,按对象wheel属性计算差集?

问题解决:Ruby跨类数组差集按属性比较的正确实现

核心问题分析

你之前的<=>方法存在两个关键错误:

  1. 错误使用了未定义的car变量,应该引用当前实例的wheel属性(用self.wheel或直接wheel);
  2. 未处理跨类比较的边界情况,且BigCar类也需要同步实现正确的<=>方法,否则Car与BigCar实例无法通过wheel属性判定相等。

正确实现代码

Car类实现

class Car
  include Comparable
  attr_reader :wheel

  def initialize(wheel)
    @wheel = wheel
  end

  def <=>(other)
    # 先校验对方是否具备wheel属性,避免报错
    return nil unless other.respond_to?(:wheel)
    wheel <=> other.wheel
  end
end

BigCar类实现

class BigCar
  include Comparable
  attr_reader :wheel

  def initialize(wheel)
    @wheel = wheel
  end

  def <=>(other)
    return nil unless other.respond_to?(:wheel)
    wheel <=> other.wheel
  end
end

验证效果

执行以下测试代码:

cars = [Car.new(4), Car.new(6), Car.new(8), Car.new(10)]
big_cars = [BigCar.new(4), BigCar.new(6), BigCar.new(8)]

# 输出仅包含wheel=10的Car实例
p cars - big_cars

原理说明

Ruby的Array#-操作基于元素的相等性判断(即==方法),而混入Comparable模块后,==会自动基于<=>的结果生成:当两个对象的<=>返回0时,==返回true,此时差集操作会将匹配的元素移除。

内容的提问来源于stack exchange,提问作者Dedy Puji

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 21:05:32