Yoihito
Yoihito

Reputation: 378

Ruby: Create new string at every replacement

How to create a list of strings with only one replace of matched pattern in ruby.

For example:

The given string is "aaaazzzazazaaaazzzazaaaazz". I need to replace "aaaa" with "A". So I would get a such list:

Upvotes: 2

Views: 87

Answers (1)

Stefan
Stefan

Reputation: 114208

You could use String#scan with a block:

str = "aaaazzzazazaaaazzzazaaaazz"
str.scan(/aaaa/) { |m| puts "#{$`}A#{$'}" }

Output:

Azzzazazaaaazzzazaaaazz
aaaazzzazazAzzzazaaaazz
aaaazzzazazaaaazzzazAzz

$` and $' are global variables, referencing the strings to the left and to the right of the last match.

Upvotes: 5

Related Questions