Dan*_*min -2 ruby arrays 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
}
Run Code Online (Sandbox Code Playgroud)
对我做错了什么的想法?
无需打扰那些太空船操作员值(-1,0,1)
order = ['negative', 'neutral', 'positive']
data.sort_by {|d| order.index(d.connotation)}
Run Code Online (Sandbox Code Playgroud)
connotations = {"positive" => 1, "negative" => -1, "neutral" => 0}
res.sort_by { |re| conotations[re.connotation] }
Run Code Online (Sandbox Code Playgroud)