加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 如何从数组中删除不需要的东西?

发布时间:2020-12-17 03:09:38 所属栏目:百科 来源:网络整理
导读:好的,我有一个看起来像这样的数组. ["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","
好的,我有一个看起来像这样的数组.

["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 [: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

解决方法

快速ruby变种是:

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","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"]

你如何在这段代码中看到:我们只是将结果保存在变量中.
那么,我们可以将数据存储在rails中?
您可以使用user_model,也可以将此数据存储在内存中.

创建这样的东西:

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)

我更喜欢在Class中存储状态内存,但不要忘记清除这个类数据

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读