Reputation: 378
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:
"aaaazzzazazaaaazzzazAzz"
s = gets.strip
stor="aaaa"
sforr="A"
a = s.split(stor)
(a.length-1).times { |x| puts a[0..x].join(stor)+sforr+
a[x+1..a.count-1].join(stor) }
Upvotes: 2
Views: 87
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