Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: splitting a string without removing separators

Tags:

string

split

ruby

I need to split a string without removing the separators. Is there a simple and "Ruby oriented" way to do this?

For example, given a string like this:

str = "(This is (a test))"

what I need is this:

["(", "This", "is", "(", "a", "test", ")", ")"]

I tried using the split method for strings, using the brackets "(" and ")" as separators, but then I get them removed from the returning array. Any advice will be helpful.

like image 580
kwadr4tic Avatar asked Feb 21 '23 21:02

kwadr4tic


1 Answers

Maybe something like this:

str.scan(/\(|\)|\w+/)
like image 85
rainkinz Avatar answered Mar 07 '23 06:03

rainkinz