好吧,我有一个看起来像这样的数组。如何从数组中删除不需要的东西?
["Enter Sandman", "One", "Nothing Else Matters", "Master of Puppets", "The Unforgiven", "The Day That Never Comes", "For Whom the Bell Tolls", "Fade to Black", "Sad But True", "Wherever I May Roam", "Turn the Page", "I Disappear", "Fuel", "Cyanide", "Seek & Destroy", "Whiskey In the Jar", "All Nightmare Long", "Battery", "Welcome Home (Sanitarium)", "The Unforgiven III", "The Unforgiven II", "King Nothing", "Ride the Lightning", "No Leaf Clover", "Until It Sleeps", "...And Justice for All", "Blackened", "The Memory Remains", "Hero of the Day", "The Four Horsemen", "Orion", "Creeping Death", "St. Anger", "Harvester of Sorrow", "Don't Tread on Me", "Broken, Beat & Scarred", "Disposable Heroes", "Fight Fire With Fire", "The End of the Line", "Trapped Under Ice", "Of Wolf and Man", "Whiplash", "My Apocalypse", "Suicide & Redemption", "The Shortest Straw", "Tuesday's Gone"]
此阵列由该命令
artists = search_object.map{|x| x["trackName"]}.uniq.delete_if {|x| x == nil}
这个工作得很好,但产生的,我需要过滤掉一些更多的元素。用户将输入文本字段,当他们键入我需要缩小结果。所以例如,如果用户输入字符串“Matters”,我需要去除名称中不包含那些元素或名称的元素。所以它简单地归结为“无关紧要”。如果用户输入字母“a”,那么阵列中没有“a”的所有其他人都将被删除。
他们会来与PARAMS [:文]
我做到这一点,它的工作,但也许有一个更清洁的方式
query = params[:term]
artists = search_object.map{|x| x["trackName"]}.uniq.delete_if {|x| x == nil}
filtered = []
artists.each do |artist|
filtered << artist if artist.include?(query)
end
metallica_tracks << “活着就是死” – johnmcaliley 2010-09-23 02:08:56
一点题外话了,你可以使用'compact'而不是'delete_if {| x | x == nil}'。 – vonconrad 2010-09-23 02:25:10