From: Rick DeNatale Date: 2009-11-29T01:35:45+09:00 Subject: Re: where is grep? On Sat, Nov 28, 2009 at 11:10 AM, Robert Klemme wrote: > On 11/28/2009 08:27 AM, David A. Black wrote: >> >> Hi -- >> >> On Sat, 28 Nov 2009, Florian Gilcher wrote: >> >>> Grep is not defined on Ruby 1.9-Strings. >>> >>> It was on Ruby 1.8-Strings, but only because they were belonging to the >>> group of objects that mixed in Enumerable. >>> >>> There, grep behaves like this (line by line): >>> >>> x = "hello world baby girl" >>> x.grep(/hello/) >>> #=> ["hello world baby girl"] >>> x = "hello\nworld\nbaby\ngirl" >>> x.grep(/hello/) >>> #=> ["hello\n"] >>> >>> The same can be done in Ruby 1.9 by just splitting the String beforehand. >>> Arrays are Enumerable and thus >>> still have grep: >>> >>> x = "hello\nworld\nbaby\ngirl" >>> x.split("\n").grep(/hello/) >>> #=> ["hello"] >>> >>> Note the absence of the line-break which might be intended or not :). >> >> I would probably do this in 1.9: >> >>   string.lines.grep(/pattern/) >> >> where lines returns an enumerator. > > Why not just string.scan(/pattern/) ? Not the same thing using 1.9 irb(main):001:0> a = "abe\nbob\nfred\njim" => "abe\nbob\nfred\njim" irb(main):002:0> a.scan(/b/) => ["b", "b", "b"] irb(main):003:0> a.lines.grep(/b/) => ["abe\n", "bob\n"] a.lines.grep does the same thing that a.grep would do in 1.8, a.scan does not. -- Rick DeNatale Blog: http://talklikeaduck.denhaven2.com/ Twitter: http://twitter.com/RickDeNatale WWR: http://www.workingwithrails.com/person/9021-rick-denatale LinkedIn: http://www.linkedin.com/in/rickdenatale