From: David Alan Black Date: 2001-04-25T07:06:00+09:00 Subject: [ruby-talk:14182] Re: Ruby way to delete entries from an array On Wed, 25 Apr 2001, Dave Thomas wrote: > Jim Freeze writes: > > > I have an array where I need to delete several entries. > > Here is how I am doing it. > > > > a = ["cat\n", "dog\n", "bird \n"] > > rm = ["cat", "bird"] > > > > rm.each do |del| > > for i in (0...a.size).collect.reverse > > a.delete_at(i) if /#{del}/ =~ a[i] > > end > > end > > > > Is there a more compact way to do this? > > > Well, this is more compact. The fact that you're using regexp matches > makes it a little tricky. > > pattern = Regexp.new(rm.join('|')) > a.delete_if {|entry| entry =~ pattern } Another possibility, for those who just can't get enough iteration: a.delete_if do |e| rm.detect do |r| /#{r}/.match(e) end end > > In the general case, where the elements of 'rm' might contain meta > characters, you'd need the somewhat more cumbersome: > > pattern = Regexp.new(rm.collect {|str| Regexp.escape(str) } .join('|')) The equivalent for the above version (for completeness :-) a.delete_if do |e| rm.detect do |r| /#{Regexp.escape(r)}/.match e end end David -- David Alan Black home: dblack@candle.superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav