【问题标题】:How to sort an array by a string attribute in a predefined order如何按预定义的顺序按字符串属性对数组进行排序
【发布时间】:2015-12-22 15:19:34
【问题描述】:

我有很多评论。每条评论都有一个内涵(字符串)属性,可以是正面的、负面的或中性的。

我正在尝试构建一个sort 方法,它将所有的否定放在开头,然后是中性,然后是肯定的。另外,另一种方法相反。

我尝试了以下方法:

res.sort! { |re1,re2|
  case
  when re1.connotation == re2.connotation
    0
  when re1.connotation == "positive"
    -1
  when re1.connotation == "negative"
    1
  else
    0
  end
}

对我做错了什么有什么想法吗?

【问题讨论】:

  • 一些示例数据会很有用。

标签: arrays ruby sorting


【解决方案1】:

无需理会那些飞船运算符值(-1、0、1)

order = ['negative', 'neutral', 'positive']

data.sort_by {|d| order.index(d.connotation)}

【讨论】:

    【解决方案2】:
    connotations = {"positive" => 1, "negative" => -1, "neutral" => 0}
    res.sort_by { |re| conotations[re.connotation] }
    

    【讨论】:

    • 如果用于指定评级的词可能会发生变化,为了提高可维护性也许RATINGS = { high: "positive", middle: "neutral", low: "negative" }; connotations = { RATINGS[:high]=>1, RATINGS[:middle]=>0, RATINGS[:low]=>-1}
    【解决方案3】:
    class Review
      attr_reader :name, :connotation
      def initialize(name, connotation)
        @name = name
        @connotation = connotation
      end
    end
    
    data = [Review.new("BMW 335i",        "positive"),
            Review.new("Honda CRV",       "neutral"),
            Review.new("Porsche Boxster", "positive"),
            Review.new("Pontiac Aztec",   "negative")]
    
    data.sort_by(&:connotation)
      #=> [#<Review:0x007fa3e483f510 @name="Pontiac Aztec",@connotation="negative">,
      #    #<Review:0x007fa3e483f678 @name="Honda CRV", @connotation="neutral">,
      #    #<Review:0x007fa3e483f5d8 @name="Porsche Boxster", @connotation="positive">,
      #    #<Review:0x007fa3e483f6f0 @name="BMW 335i", @connotation="positive">]
    

    如果评级是“差”、“OK”和“好”,那么它会回到绘图板上。

    【讨论】:

      猜你喜欢
      • 2012-06-02
      • 2018-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多