Ruby idiom for all matches in a string

Hi –

What’s the ruby idiom for all the matches in a string.

x=“ABA ABBBA CBBA”
/A(B+)/.match(x)

Ultimately, I want to get [ “B”, “BBB” ]

Thanks

/A(B+)/.match(x).captures

That won’t do it; it only gets the first one. To get them all, you can
use String#scan:

irb(main):008:0> x

“ABA ABBBA CBBA”
irb(main):009:0> x.scan(/A(B+)/)
=> [[“B”], [“BBB”]]

The reason you get an array-of-arrays (which you may have to flatten
before it’s useful) is that each scan (i.e., each application of the
regex) generates a new array of captures. (This starts to look less
cumbersome when you’ve got more than one capture.) Also, #scan takes a
block, which can be handy.

David

Ah yes, #scan. You know, as much as I love #scan, it is probably the only
method I have to look up in ‘ri’ every time I use it. I can never
remember whether the block form yields an array or a matchdata or a string
or what.

Gavin

···

On Mon, 13 Oct 2003, Gavin Sinclair wrote:

On Monday, October 13, 2003, 8:34:41 AM, David wrote: