【问题标题】:Best way to sort a relation by a hash with sort values in ruby?用红宝石中的排序值通过哈希对关系进行排序的最佳方法?
【发布时间】:2014-07-04 06:08:39
【问题描述】:

目前,我有一系列不同状态的礼品卡。由于复杂的逻辑,这些状态不会保留在对象上。我的目标是按状态订购这些礼品卡。这是我当前的实现:

  @gift_cards.sort! do |a, b|
    comp = gc_sort_order[a.status] <=> gc_sort_order[b.status]
    comp.zero?? (b.expiration_date <=> a.expiration_date) : comp
  end

GiftCard#status 返回过期或激活状态。它们的“排序权重”由 gc_sort_order 这样定义:

def gc_sort_order
  {
    active: 1,
    redeemed: 2,
    expired: 3
  }
end

但是,这似乎很笨拙,我想对其进行重构,但目前还没有找到更好的解决方案。任何意见将不胜感激。

【问题讨论】:

    标签: ruby-on-rails ruby sorting activerecord hash


    【解决方案1】:
    class Reverser
      attr_reader :v
    
      def initialize(v)
        @v = v
      end
    
      def self.[](v)
        new(v)
      end
    
      def <=>(other)
        other.v <=> @v
      end
    end
    
    # status ASC, expiration_date DESC
    @gift_cards.sort_by! { |gc| [ gc_sort_order[gc.status], 
                                  Reverser[gc.expiration_date] ] }
    

    【讨论】:

      【解决方案2】:

      试试这个:

      @gift_cards.sort_by! { |gc| [-gc_sort_order[gc.status], gc.expiration_date] }.reverse
      

      【讨论】:

      • 这可以工作,但到期日期的排序是相反的。例如b.expiration_date &lt;=&gt; a.expiration_date
      猜你喜欢
      • 2014-09-28
      • 1970-01-01
      • 1970-01-01
      • 2011-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多