From: Robert Klemme Date: 2012-01-13T23:18:12+09:00 Subject: Re: negative grep On Thu, Jan 12, 2012 at 10:22 PM, Peter Vandenabeele wrote: > On Thu, Jan 12, 2012 at 9:36 PM, Chad Perrin wrote: > >> On Fri, Jan 13, 2012 at 05:26:59AM +0900, Matt Lawrence wrote: >> > On Fri, 13 Jan 2012, Robert Klemme wrote: >> > >> > >I'd use #select with inverted condition or #reject >> > > >> > >irb(main):005:0> a.select {|s| /0/ !~ s} >> > >> > That worked perfectly, thank you.  A a sysadmin, I use "grep -v" >> > quite a bit and I was hoping that the grep method in Ruby had a >> > similar capability.  Using select is a bit wordier and not quite as >> > apparent as to what is going on, but it works very well. >> >> Do you object to reject? >> > > Well, a 'v' option, equivalent to the UNIX grep seems quite straightforward > to conceive? > > peterv@ASUS:~$ ruby -v > ruby 1.9.3p0 (2011-10-30 revision 33570) [i686-linux] > peterv@ASUS:~$ echo -e "abc\ndef\nghi" | grep abc > abc > peterv@ASUS:~$ echo -e "abc\ndef\nghi" | grep -v abc > def > ghi > peterv@ASUS:~$ ruby -e 'puts %w{ abc def ghi}.grep(/abc/)' > abc > peterv@ASUS:~$ ruby -e 'puts %w{ abc def ghi}.grep(/abc/v)' > -e:1: unknown regexp option - v > > Having "def" and "ghi" as a result here would be nice :-) Pretty easy to do: module Enumerable def grep_v(cond) select {|x| not cond === x} end end irb(main):006:0> a=10.times.map &:to_s => ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] irb(main):007:0> a.grep /0/ => ["0"] irb(main):008:0> a.grep_v /0/ => ["1", "2", "3", "4", "5", "6", "7", "8", "9"] Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/