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"] 你如何在这段代码中看到:我们只是将结果保存在变量中. 创建这样的东西: 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中存储状态内存,但不要忘记清除这个类数据 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
- Exchange:使用XML请求在EWS对话中查找项目?
- 《从零开始学Swift》学习笔记(Day 45)――重写
- 关于dwr消除服务器端出错时弹出alter的解决方案
- objective-c – 在Mac OS X上的触控板中知道手指
- c# – webapi .net核心得到nginx connect()失败(
- 选择返回时没有oracle select into变量?
- ruby-on-rails – 如何通过覆盖诸如respond_with
- cocos2d-x-3.10 之Mac系统Xcode环境搭建教程
- swift:当单元格中的按钮被点击时如何获取indexp
- ruby-on-rails – 你能检查一下ruby on rails中同
热点阅读