Forum: Ruby Re: Beginner gsub and ri questions

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Jamal M. (Guest)
on 2006-04-18 01:14
(Received via mailing list)
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
This topic is locked and can not be replied to.