ruby - ruby 中的排序列表

标签 ruby arrays list sorting

我有以下 Linea 类(class)

class Linea
   include Comparable
   attr_accessor :maxcap, :capatuale, :citta1, :citta2, :lineac

   def initialize(c1, c2, maxc)
      raise CapacitaIllegale if maxc <= 0
      @maxcap = maxc
      @capatuale = maxc
      @citta1 = c1
      @citta2 = c2
      @lineac = []
      @lineac.push(c1)
      @lineac << c2
   end

    def <=> (l)
      if(l.is_a?(Linea))
        if (l.maxcap>@maxcap)
          return l.maxcap
        end
        if(l.maxcap==@maxcap)
          if (l.citta1.pop + l.citta2.pop>@<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="36555f42425707184659461d76555f4242570418465946" rel="noreferrer noopener nofollow">[email protected]</a>)
            return l.maxcap
          end
        end
      end
      return -1
    end
  end

在 Rete 类之后,我想插入 Linea 并使用 <=> so 进行排序;

  class Rete
     attr_accessor :lineec, :guasto_seg

     def initialize()
      @rete = []
      @guasto_seg = []
     end

     def aggiungi_linea(c1, c2, maxc)
        l = Linea.new(c1, c2, maxc)
        unless (citta_presente(c1, c2))
           @rete << l
           @rete.sort { |l1,l2| l1<=>l2 if l1.is_a?(Linea) and l2.is_a?(Linea) }
        else
           raise LineaGiaEsistente
        end
     end

     + some diferent method   

  end

我想询问如何使用它进行排序的解释,如果我的正确的话,就是如果 <=> 完成并调用排序,那么正确。?????? 请尽快给我答复,谢谢。

最佳答案

为了有助于排序,<=>方法的行为必须如下所示:

big_linea <=> small_linea #=> 1
big_linea <=> equally_big_linea #=> 0
small_linea <=> big_linea #=> -1

当它起作用时,你应该能够做到

@rete.sort #no block needed

关于ruby - ruby 中的排序列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9421426/

相关文章:

c++ - 使用 gets(a) 而不是 cin.getline(a,20) 有什么好处?

java - 使用 Java8 流过滤 map 键后映射到列表

ruby-on-rails - 在不保存的情况下使用 acts_as_state_machine 转换方法

ruby - sprintf 格式不符合预期

ruby - Rails 5 - 保存回滚,因为嵌套模型父模型未在子模型之前保存

php - 基于键将大型关联数组转换为局部变量

ruby - 如何巧妙地进行数组加法?

java - 我们如何动态分配和增长数组

python - 列表的标准差

python log2 超过列表列表的索引