我正在尝试清理一个遍历推入数组的数据的方法。大概是这样的:
def sort_by_title(authors)
general = []
fiction = []
factual = []
food = []
other = []
authors.each do |a|
if a.tag.include?('General')
general << a
elsif a.tag.include?('Historical')
fiction << a if a.tag.include?('iction')
factual <<a if a.tag.include?('actual')
elseif a.tag.include?('Food')
food << a
else
other << a
end
end
(general + fiction + factual + food + other).flatten
end
end鲁博科普正在用:Metrics/AbcSize and Metrix/Perceived Complexity攻击我。有没有更干净的方法可以这样做呢?
发布于 2018-12-14 23:32:42
我会选择case
authors.each_with_object(Hash.new { |h, k| h[k] = [] }) do |a, hash|
case a.tag
when /General/ then h[:general] << a
when /Historical.*iction/ then h[:fiction] << a
when /Historical.*actual/ then h[:factual] << a
when /Food/ then h[:food] << a
else h[:other] << a
end.values.flatten或者,使用Enumerable#sort_by使用更令人兴奋和语义正确的方法
authors.sort_by do |a|
[
10 if a.tag.include?('General'),
if a.tag.include?('iction')
8
elsif if a.tag.include?('actual')
6
end if a.tag.include?('Historical'),
4 if a.tag.include?('Food'),
2
].compact.sum
end发布于 2018-12-14 23:16:28
您可以使用#group_by
def sort_by_title(authors)
grouped = authors.group_by do |a|
if a.tag.include?('General')
:general
elsif a.tag.include?('Historical')
:fiction if a.tag.include?('iction')
:factual if a.tag.include?('actual')
elsif a.tag.include?('Food')
:food
else
:other
end
end
grouped.values.flatten
end编辑:
为了让它更清晰,你可以提取关于流派的方法:
class Author
def genre
if tag.include?('General')
:general
elsif tag.include?('Historical')
:fiction if tag.include?('iction')
:factual if tag.include?('actual')
elsif tag.include?('Food')
:food
else
:other
end
end
end
def sort_by_title(authors)
authors.group_by(&:genre).values.flatten
end发布于 2018-12-15 07:41:20
您需要对它们进行分组还是排序?如果只是排序,是否可以使用带有查找字段的sort_by?
TAGS = {
'General' => 1,
'Fiction' => 2,
'Factual' => 3,
'Food' => 4,
'Other' => 5
}
authors = [
{ name: 'Joe', tag: 'General' },
{ name: 'Sue', tag: 'Fiction' },
{ name: 'Sally', tag: 'Food' },
{ name: 'Oliver', tag: 'Factual' },
{ name: 'Bob', tag: 'Other' },
{ name: 'Billy', tag: 'General' }
]
sorted_authors =
authors.sort_by do |author|
TAGS[author[:tag]] # This would be author.tag in your example
end
puts sorted_authors收益率
{:name=>"Joe", :tag=>"General"}
{:name=>"Billy", :tag=>"General"}
{:name=>"Sue", :tag=>"Fiction"}
{:name=>"Oliver", :tag=>"Factual"}
{:name=>"Sally", :tag=>"Food"}
{:name=>"Bob", :tag=>"Other"}https://stackoverflow.com/questions/53781991
复制相似问题