2015-12-22 87 views
-2

我有一組評論。每個評論都有一個正面,負面或中性內涵(字符串)的屬性。如何按照預定義順序通過字符串屬性對數組進行排序

我試圖建立一個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

一些示例數據會很有用。 –

+3

這是怎麼回事? – sawa

回答

8

無需與運營商飛船值理會(-1,0,1)

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

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

好點... :) – ndn

+0

真棒,作品像魅力! –

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

如果用於指定評分的詞語可能會改變,爲了提高可維護性,可能是「RATINGS = {high:」positive「,middle:」neutral「,low:」negative「};內涵= {RATINGS [:high] => 1,RATINGS [:middle] => 0,RATINGS [:low] => - 1}'。 –

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

如果收視率的 「壞」, 「好」 和 「好」,它會回到繪圖板。

+0

好,Cary! –

相關問題