加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 对象与fixnum的比较

发布时间:2020-12-17 02:47:24 所属栏目:百科 来源:网络整理
导读:我希望能够将对象与fixnums进行比较. class Dog include Comparable def =(other) 1 endend 鉴于上述课程,为什么这样做: dog = Dog.newarray = [2,1,4,dog]array.min= 1 但这不是: dog = Dog.newarray = [dog,2,4]array.minArgumentError: comparison of F
我希望能够将对象与fixnums进行比较.

class Dog
  include Comparable
  def <=>(other)
    1
  end
end

鉴于上述课程,为什么这样做:

dog = Dog.new
array = [2,1,4,dog]
array.min
=> 1

但这不是:

dog = Dog.new
array = [dog,2,4]
array.min
ArgumentError: comparison of Fixnum with Dog failed
    from (irb):11:in `each'
    from (irb):11:in `min'
    from (irb):11

当对象是第一个元素时,为什么我不能将对象与数字进行比较?
有什么办法可以解决这个问题吗?我希望Dog对象在与数组中的任何其他值进行比较时始终是最大值,这就是我在< =>中将其设置为1的原因.方法.

谢谢!

解决方法

要与数字类型进行比较,您可以实现 coerce

class Dog
  include Comparable

  def initialize(age)
    @age = age
  end

  def <=>(other)
    @age <=> other
  end

  def coerce(numeric)
    [numeric,@age]
  end
end

Dog.new(5) <=> Dog.new(5)  #=>  0
Dog.new(5) <=> 1           #=>  1
         1 <=> Dog.new(5)  #=> -1

[1,3,Dog.new(2)].sort
#=> 1,#<Dog @age=2>,3]

可以在不实现< =>的情况下实现上述排序.并强迫使用sort_by

class Dog
  attr_accessor :age

  def initialize(age)
    @age = age
  end
end

[1,Dog.new(2)].sort_by { |obj| obj.is_a?(Dog) ? obj.age : obj }
#=> 1,3]

还有min_bymax_by.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读