【问题标题】:Ruby custom sorting returns -1 +1 instead of arrayRuby 自定义排序返回 -1 +1 而不是数组
【发布时间】:2014-01-19 13:06:58
【问题描述】:

我正在尝试实现我的第一个 ruby​​ 排序算法。这个算法基于一些特定的规则(“总是更喜欢 xxx 类型的对象而不是 yyy 类型的对象”),如果这些规则都没有触发,它使用 ruby​​ -操作符。我在 ruby​​-on-rails 一对多关联上执行此操作。

问题是这个算法不返回数组本身,它只返回-1或1,比较的结果..但我实际上不明白为什么,因为我的结果只在排序块中返回.

这是我当前的代码:

def sort_products!
  products.sort! do |p1, p2|
    result = 0

    # Scalable Products are always the last ones in order
    if p1.class.name == "ScalableProduct"
      result = -1
    elsif p2.class.name == "ScalableProduct"
      result = 1
    end

    if result == 0
      # Put products producing electricity and heating down
      if p1.can_deliver_electricity?
        result = -1
      elsif p2.can_deliver_electricity? 
        result = 1
      end
    end

    # Else: Just compare names
    result = p1.name <=> p2.name if result == 0
    result
  end
end

【问题讨论】:

  • 你能显示调用该方法的代码吗?
  • 请打印出 sort_products 中的 products 数组!调用排序之前的方法!方法。

标签: ruby-on-rails ruby arrays sorting


【解决方案1】:

在我看来,这里的最佳做法是在 Product 模型中实现 &lt;=&gt;。您需要包含 Comparable 模型才能实现此目的:

class Product
  include Comparable

  def <=>(another_product)
    # Compare self with another_product
    # Return -1, 0, or 1
  end
end

那么你的排序方式会简化为:

def sort_products!
  products.sort!
end

【讨论】:

    【解决方案2】:

    将括号的do..end 更改为块的分隔符。它是先排序,然后在结果上使用块(因为precedence of the do..end syntax)。使用括号,它使用块作为排序块,这正是你想要的。

    此外,在您的比较中,如果您的两个产品都是ScalableProduct,那么您将不会以合理的方式订购它们。如果它们同时是ScalableProduct,您可能希望将result 保留为0,以便返回到按名称进行比较。与can_deliver_electricity? 相同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-05
      • 1970-01-01
      • 2015-12-07
      • 1970-01-01
      • 1970-01-01
      • 2019-07-22
      • 1970-01-01
      • 2016-02-19
      相关资源
      最近更新 更多