在 Ruby 中对数组进行排序,忽略冠词(“the"、“a"、“an") [英] Sort an array in Ruby ignoring articles ("the", "a", "an")

查看:42
本文介绍了在 Ruby 中对数组进行排序,忽略冠词(“the"、“a"、“an")的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my application I need to show a list of songs. Right now I'm doing this:

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

不幸的是,这意味着The Notorious BIG"将使用 T 进行排序,而我希望他使用 N 进行排序(即,我想忽略冠词——the"、a"和an"——- 用于排序.

Unfortunately, this means that "The Notorious B.I.G" will sort with the T's while I want him to sort with the N's (i.e., I want to ignore articles -- "the", "a", and "an" -- for the purposes of sorting.

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

My first thought was to do this:

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

但是好像不行.想法?

推荐答案

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

My favorite approach to these kind of problems is to store an extra sort_order column in the database.

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

That way when you have 10000 songs that you would like to page through, you can do that in SQL and avoid having to pull them all back.

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

Its simple to add a before_save filter to keep this column in sync.

不改变架构的干净解决方案是:

The cleanish solution, without schema changes is:

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 中对数组进行排序,忽略冠词(“the"、“a"、“an")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆