Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 17th, 2012  |  syntax: None  |  size: 0.37 KB  |  hits: 18  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. How do I limit the number of replacements when using gsub?
  2. str = 'aaaaaaaaaa'
  3. count = 5
  4. p str.gsub(/a/){if count.zero? then $& else count -= 1; 'x' end}
  5. # => "xxxxxaaaaa"
  6.        
  7. str = 'aaaaaaaaaa'
  8. # The following is so that the variable new_string exists in this scope,
  9. # not just within the block
  10. new_string = str
  11. 5.times do
  12.   new_string = new_string.sub('a', 'x')
  13. end