Natalia Natalia - 1 month ago 7
Ruby Question

How do I figure out the indexes of where a string was split?

Iā€™m using Rails 4.2.7 (Ruby 2.3). I use the following to split a string based on a regular expression

my_string.split(/\W+/)


My question is, how can I get an equivalent array of numbers in which each number represents the index of where the splits occurred? If no splits occurred, I would expect the array to only contain an element with ā€œ-1ā€.

Answer

So, you don't want to split, you just want the indices?

a = []
"Hello stack overflow".scan(/\W+/){a<<Regexp.last_match.begin(0)}
a
#=> [5, 11]

An empty array would mean that no split occured.

Edit : Shorter version could be

"Hello stack overflow".enum_for(:scan, /\W+/).map{Regexp.last_match.begin(0)}
#=> [5, 11]