如何按预定义的顺序按字符串属性对数组进行排序

时间:2015-12-22 15:19:35

标签: arrays ruby sorting

我有一系列的评论。每个评论都有一个正面,负面或中性的内涵(字符串)属性。

我正在尝试构建一个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
}

对我做错了什么的想法?

3 个答案:

答案 0 :(得分:8)

无需担心这些太空船操作员值(-1,0,1)

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

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

答案 1 :(得分:5)

connotations = {"positive" => 1, "negative" => -1, "neutral" => 0}
res.sort_by { |re| conotations[re.connotation] }

答案 2 :(得分:2)

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">]

如果评级为“差”,“好”和“好”,则会回到绘图板。