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

Tom*_*man 4 ruby ruby-on-rails

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

Song.all.sort {|x,y| x.artist.name <=> y.artist.name }
Run Code Online (Sandbox Code Playgroud)

不幸的是,这意味着"臭名昭着的大"将与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, '') }
Run Code Online (Sandbox Code Playgroud)

但它似乎没有用.思考?

Sam*_*ron 12

我最喜欢的解决这类问题的方法是在数据库中存储一个额外的 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 }
Run Code Online (Sandbox Code Playgroud)