Currently i am splitting a string by pattern, like this:
outcome_array=the_text.split(pattern_to_split_by)
The problem is that the pattern itself that i split by, always gets omitted.
How do i get it to include the split pattern itself?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Thanks to Mark Wilkins for inpsiration, but here’s a shorter bit of code for doing it:
or:
See below the fold for an explanation.
Here’s how this works. First, we split on “on”, but wrap it in parentheses to make it into a match group. When there’s a match group in the regular expression passed to
split, Ruby will include that group in the output:Now we want to join each instance of “on” with the preceding string.
each_slice(2)helps by passing two elements at a time to its block. Let’s just invokeeach_slice(2)to see what results. Sinceeach_slice, when invoked without a block, will return an enumerator, we’ll applyto_ato the Enumerator so we can see what the Enumerator will enumerator over:We’re getting close. Now all we have to do is join the words together. And that gets us to the full solution above. I’ll unwrap it into individual lines to make it easier to follow:
But there’s a nifty way to eliminate the temporary
band shorten the code considerably:mappasses each element of its input array to the block; the result of the block becomes the new element at that position in the output array. In MRI >= 1.8.7, you can shorten it even more, to the equivalent: