kwadr4tic
kwadr4tic

Reputation: 796

Ruby: splitting a string without removing separators

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.

Upvotes: 4

Views: 1001

Answers (1)

rainkinz
rainkinz

Reputation: 10404

Maybe something like this:

str.scan(/\(|\)|\w+/)

Upvotes: 8

Related Questions