开发者

How do I remove unwanted from an array?

Ok so I have an array that looks like this.

["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",开发者_JAVA技巧 "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"]

This array is generated by this command

artists = search_object.map{|x| x["trackName"]}.uniq.delete_if {|x| x == nil}

this works well but I need to filter out some more elements. The user will type in the textfield and as they type i need to narrow the results. So for example if the user types the string "Matters" i need to take out the elements that dont have that in the name or like the name. So it narraws down to "Nothing Else Matters". If the user enters the letter "a" then all the others in the array that dont have an "a" get deleted.

they will come in with the params[:text]

I did this and it worked but maybe there is a cleaner way

 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


the fast ruby variant is:

albums = ["hello kitty", "bad day", "all is good", "day is okay"]

def filter_word_in(word,array)
    array.delete_if { |data| !data.match(word) }
    return array
end

result1 = filter_word_in("y", albums)
puts result1.inspect # => ["hello kitty", "bad day", "day is okay"]

result2 = filter_word_in("ay", result1)
puts result2.inspect # => ["bad day", "day is okay"]

result3 = filter_word_in("day", result2)
puts result3.inspect # => ["bad day", "day is okay"]

result4 = filter_word_in("day i",result3)
puts result4.inspect # => ["day is okay"]

How you can see in this code: we just save our result in variables. So, where we can store our data in rails? You can use user_model for this, or you can just store this data in memory.

Create something like this:

class UserSongMemory
    attr_accessor :memory

    def initialize
        @memory = []
    end

    def push(id, data)
        @memory << {id => data}
    end

    def pop(id)
        @memory.delete_if {|obj| obj.id == id}
    end
end

user_memory = UserSongMemory.new
user_memory.add(@user.id, params[:inputed_string])

# after our calculations
user.pop(@user.id)

I prefer to store state memory in Class, but don't forget to clean this class-data


I would do this:

term, fname =  params[:term], "trackName"
filtered = search_object.map {|x| x[fname] if x[fname].match(term) }.compact.uniq

This approach eliminates the need for two loops, one for collection and other selection. The uniq and compact methods are there as per your requirement.


The Array class offers you the "reject" method to remove unwanted elements from your array.


Here's a slightly different approach, and my reasoning.

Reason:
I'm imagining a list on a webpage with a textbox that allows you to type a substring of your desired selection to filter down to that item. As such, my assumption is that your users will ONLY ever type a substring. These aren't power users who will be regex matching for their desired track. By just using select and include? you can limit that regex power, as people suggested, without the added complexity. Regex is a bit like using a machine gun to kill a fly in this example.

Code:
#I renamed the array, since it was a list of songs, not artists
songs.select {|s| s.upcase.include?(query.upcase)}
You could leave the upcase off if you want the query to be case sensitive

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜