好的,我有一个看起来像这样的数组。
["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",我需要排除那些名称中没有或类似于该名称的元素。所以它缩小到了"Nothing Else Matters"。如果用户输入字母"a",则数组中所有没有"a"的元素都将被删除。
它们将通过params[:text]传递进来。
我已经这样做了,它可以工作,但也许有更简洁的方法。
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
compact
来代替delete_if {|x| x == nil}
。 - vonconrad