Replace outside comma with newline I'm looking for a better alternative to replace insert + gsub.

hobbies = "Hobbies: \nsports (basketball, gym), foods (hamburger, steak, pasta), reading, movie, justfortesting((test1, test2), test3)"
print "\n\nBefore: \n\n" + hobbies
counter = 0
for i in 0...hobbies.length do
    case hobbies[i]
    when '('; counter += 1
    when ')'; counter -= 1
    when ','; hobbies.insert i + 1, "\n" if counter == 0
    end
end
counter = nil
hobbies.gsub!(",\n", "\n")
hobbies.gsub!("\n ", "\n")
print "\n\nAfter: \n\n" + hobbies




Output:

Before: 

Hobbies: 
sports (basketball, gym), foods (hamburger, steak, pasta), reading, movie, justfortesting((test1, test2), test3)

After: 

Hobbies: 
sports (basketball, gym)
foods (hamburger, steak, pasta)
reading
movie
justfortesting((test1, test2), test3)
How about:

hobbies = "Hobbies: \nsports (basketball, gym), foods (hamburger, steak, pasta), reading, movie, justfortesting((test1, test2), test3)"
print "\n\nBefore: \n\n" + hobbies

counter = 0
hobbies = hobbies.chars.map do |char|
  next "\n" if char == ',' and counter == 0
  counter += 1 if char == '('
  counter -= 1 if char == ')'
  char
end.join
counter = nil

print "\n\nAfter: \n\n"
hobbies.each_line do |line|
  puts line.lstrip
end