Re: Beginner gsub and ri questions

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.


text = “DOG Dog mouse dog rat dOg”
find = “dog”
replace = “cat”
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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs