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

ruby-on-rails – 覆盖Ruby的宇宙飞船操作符<=>

发布时间:2020-12-17 03:51:37 所属栏目:百科 来源:网络整理
导读:我试图覆盖 Ruby的 = (太空飞船)运算符对苹果和橙子进行分类,以便苹果首先按重量分类,然后是橙子,按甜度分类.像这样: module Fruity attr_accessor :weight,:sweetness def =(other) # use Array#= to compare the attributes [self.weight,self.sweetness]
我试图覆盖 Ruby的< => (太空飞船)运算符对苹果和橙子进行分类,以便苹果首先按重量分类,然后是橙子,按甜度分类.像这样:

module Fruity
  attr_accessor :weight,:sweetness

  def <=>(other)
    # use Array#<=> to compare the attributes
    [self.weight,self.sweetness] <=> [other.weight,other.sweetness]
  end
  include Comparable
end

class Apple
include Fruity

def initialize(w)
  self.weight = w
end

end

class Orange
include Fruity

def initialize(s)
  self.sweetness = s
end

end

fruits = [Apple.new(2),Orange.new(4),Apple.new(6),Orange.new(9),Apple.new(1),Orange.new(22)]

p fruits

#should work?
p fruits.sort

但这不起作用,有人可以告诉我这里做错了什么,或者更好的方法吗?

解决方法

你的问题是你只是初始化任何一方的属性,另一方仍然是零. nil不在数组#< =>中处理方法,最终杀死排序.

有几种方法可以解决这个问题,首先是这样的

[self.weight.to_i,self.sweetness.to_i] <=> [other.weight.to_i,other.sweetness.to_i]

nil.to_i给你0,这将使这工作.

(编辑:李大同)

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

    推荐文章
      热点阅读