Forum: Ruby Building an array of matching strings.

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
56f2ce19706d05d18b5b66483aa13f98?d=identicon&s=25 ljz (Guest)
on 2005-11-21 00:00
(Received via mailing list)
I want to search through a block of text and build an array of all
strings contained within this text that match a given pattern.  I know
the following hack will work, but it seems like a misuse of the gsub
method:

  # Assume that 'text' contains the block of text and that 'pat'
  # is a Regexp instance containing the pattern to match.

  matchingStrings = []
  text.gsub(pat) {
    |m|
    matchingStrings << m
  }

Is there a cleaner and elegant way to do this?

Thanks in advance.
4299e35bacef054df40583da2d51edea?d=identicon&s=25 james (Guest)
on 2005-11-21 00:08
(Received via mailing list)
On Nov 20, 2005, at 5:00 PM, Lloyd Zusman wrote:

>     |m|
>     matchingStrings << m
>   }
>
> Is there a cleaner and elegant way to do this?

matches = text.scan(...)

Hope that helps.

James Edward Gray II
E34b5cae57e0dd170114dba444e37852?d=identicon&s=25 logancapaldo (Guest)
on 2005-11-21 00:08
(Received via mailing list)
On 11/20/05, Lloyd Zusman <ljz@asfast.com> wrote:
> text.gsub(pat) {
> Lloyd Zusman
> ljz@asfast.com
> God bless you.


I think what you want is matchingStrings = text.scan(pat)
132a94ca65959bda6c74fae54bff2425?d=identicon&s=25 ezra (Guest)
on 2005-11-21 00:12
(Received via mailing list)
On Nov 20, 2005, at 3:00 PM, Lloyd Zusman wrote:

>     |m|
>     matchingStrings << m
>   }
>
> Is there a cleaner and elegant way to do this?
>
> Thanks in advance.
>


result_array = text.scan(/pat/)


That will build an array in result_array of all the matches to /pat/


HTH-

-Ezra Zygmuntowicz
WebMaster
Yakima Herald-Republic Newspaper
ezra@yakima-herald.com
509-577-7732
56f2ce19706d05d18b5b66483aa13f98?d=identicon&s=25 ljz (Guest)
on 2005-11-21 00:20
(Received via mailing list)
Ezra Zygmuntowicz <ezra@yakima-herald.com> writes:

>>   matchingStrings = []
>
> result_array = text.scan(/pat/)
>
>
> That will build an array in result_array of all the matches to /pat/

Aha!  I had forgotten about the 'scan' method!  Thanks to all of you who
responded.
D1ae7c2dace391a23a458fe8bec07d0b?d=identicon&s=25 tomrossi7 (Guest)
on 2005-11-21 03:57
(Received via mailing list)
What if we wanted to expand it a little?  For instance, Iets say the
person has a typo like phat instead of pat.  Is there a good method for
searching and returning CLOSEST matches but not exact?
This topic is locked and can not be replied to.