gpt4 book ai didi

ruby-on-rails - 在 Ruby 中对数组进行排序,忽略文章 ("the"、 "a"、 "an")

转载 作者:数据小太阳 更新时间:2023-10-29 07:22:50 26 4
gpt4 key购买 nike

在我的应用程序中,我需要显示歌曲列表。现在我正在这样做:

Song.all.sort {|x,y| x.artist.name <=> y.artist.name }

不幸的是,这意味着“The Notorious B.I.G”将按 T 排序,而我希望他按 N 排序(即,我想忽略冠词——“the”、“a”和“an”- - 用于排序。

我的第一个想法是这样做:

Song.all.sort {|x,y| x.artist.name.gsub(/^(the|a|an) /i, '') <=> y.artist.name.gsub(/^(the|a|an) /i, '') }

但是好像不行。想法?

最佳答案

我最喜欢解决这类问题的方法是在数据库中存储一个额外 sort_order 列。

这样当您有 10000 首歌曲要翻页时,您可以在 SQL 中执行此操作,而不必将它们全部拉回。

添加一个 before_save 过滤器以保持此列同步很简单。

没有架构更改的干净解决方案是:

class Artist
def sortable_name
self.name.sub(/^(the|a|an)\s+/i, '')
end
end

class Song
def sortable_name
# note the - is there so [Radio] [head on] and [Radiohead] [karma police]
# are not mixed in the ordering
"#{artist.sortable_name} - #{name}"
end
end

# breaks ties as well
Song.all.sort_by { |song| song.sortable_name }

关于ruby-on-rails - 在 Ruby 中对数组进行排序,忽略文章 ("the"、 "a"、 "an"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1402915/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com