我有一系列音乐曲目,在这个阵列中,由于在多张专辑中发行,同一首歌可以多次显示.我试图从数组中删除它们,以便只在列表中显示真正的唯一.
哈希看起来像这样:
"tracks" => [ [0] { "id" => 1,"Title" => "Intergalactic","ArtistName" => "Beastie Boys" },[1] { "id" => 2,"ArtistName" => "Beastie Boys" } ]
解决方法
如果您使用的是ActiveSupport,则可以使用uniq_by,如下所示:
tracks.uniq_by {|track| track["title"]}
如果没有,那么您可以自己轻松实现它. See this.
# File activesupport/lib/active_support/core_ext/array/uniq_by.rb,line 6 def uniq_by hash,array = {},[] each { |i| hash[yield(i)] ||= (array << i) } array end