tags:

views:

53

answers:

2

In other languages regexp you can use //g for a global match.

However, in Ruby:

"hello hello".match /(hello)/

Only captures one hello

How do I capture all hello?

+3  A: 

use String#scan. It will return an array of each match, or you can pass a block and it will be called with each match.

All the details at http://ruby-doc.org/core/classes/String.html#M000812

wuputah
+2  A: 

You can use the scan method. The scan method will either give you an array of all the matches or, if you pass it a block, pass each match to the block.

"hello1 hello2".scan(/(hello\d+)/)   # => [["hello1"], ["hello2"]]

"hello1 hello2".scan(/(hello\d+)/).each do|m|
  puts m
end

I've written about this method, you can read about it here near the end of the article.

AboutRuby
No need to do `each`. Just `.scan(...){|m|...}`
Nakilon