0
\$\begingroup\$

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)
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

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
\$\endgroup\$
1
  • \$\begingroup\$ #join looks great! And for the last part, lines.map(&:lstrip).join will do. So like end.join.lines.map(&:lstrip).join. \$\endgroup\$ Jun 14, 2014 at 9:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.