Re: Beginner gsub and ri questions


#1

Thanks, Austin. I’m posting my current solution below. There’s
probably a more elegant way of counting the number of replacements using
the MatchData object or Regexp implicit variables, but I haven’t figured
that out yet.

Jamal

text = “DOG Dog mouse dog rat dOg”
find = “dog”
replace = “cat”
find = Regexp.new(Regexp.escape(find), Regexp::IGNORECASE)

i = 0
text = text.gsub(find) {|match|i += 1; replace}
s = i.to_s + " replacement"
s += “s” unless i == 1

puts(text) # cat cat mouse cat rat cat
puts(s) # 4 replacements