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 当对象是第一个元素时,为什么我不能将对象与数字进行比较? 谢谢! 解决方法
要与数字类型进行比较,您可以实现
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] 可以在不实现< =>的情况下实现上述排序.并强迫使用 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] 还有 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |