好吧,我有一個看起來像這樣的數組。如何從數組中刪除不需要的東西?
["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