Arrays 如何按预定义顺序按字符串属性对数组排序
我有一系列的评论。每个评论都具有肯定、否定或中立的内涵属性(字符串) 我正在尝试建立一个排序方法,将所有的负数放在开头,然后是中性数,然后是正数。另外,还有另一种方法可以反过来做 我尝试了以下方法:Arrays 如何按预定义顺序按字符串属性对数组排序,arrays,ruby,sorting,Arrays,Ruby,Sorting,我有一系列的评论。每个评论都具有肯定、否定或中立的内涵属性(字符串) 我正在尝试建立一个排序方法,将所有的负数放在开头,然后是中性数,然后是正数。另外,还有另一种方法可以反过来做 我尝试了以下方法: res.sort! { |re1,re2| case when re1.connotation == re2.connotation 0 when re1.connotation == "positive" -1 when re1.connotation == "ne
res.sort! { |re1,re2|
case
when re1.connotation == re2.connotation
0
when re1.connotation == "positive"
-1
when re1.connotation == "negative"
1
else
0
end
}
关于我做错了什么有什么想法吗?不必为那些太空船操作符值(-1,0,1)操心
connotations = {"positive" => 1, "negative" => -1, "neutral" => 0}
res.sort_by { |re| conotations[re.connotation] }
课堂复习
属性读取器:名称,:内涵
def初始化(名称、内涵)
@name=name
@内涵=内涵
结束
结束
数据=[Review.new(“BMW 335i”,“正面”),
审查。新(“本田CRV”,“中性”),
评论:全新(“保时捷Boxster”,“正面”),
审查。新(“庞蒂亚克阿兹特克”,“负面”)]
数据。排序依据(&:内涵)
#=> [#,
# #,
# #,
# #]
如果评级为“差”、“好”和“好”,它将回到绘图板上。一些样本数据将是有用的。如果用于指定评级的词语可能会改变,为了提高可维护性,可能
评级={高:“正”,中:“中性”,低:“负”};内涵={RATINGS[:high]=>1,RATINGS[:middle]=>0,RATINGS[:low]=>1}
。
order = ['negative', 'neutral', 'positive']
data.sort_by {|d| order.index(d.connotation)}
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">]