Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split Ruby string by "\r\n"?

Tags:

string

split

ruby

Given a string like:

s = "G o o d\r\nDay\r\n\r\n\r\nStack\r\n\r\nOverflow\r\n"

I would like to:

  • Split it by (\r\n)+, i.e. I would like to get: ["G o o d", "Day", "Stack", "Overflow"]

    I tried s.split(/(\r\n)+/) but it doesn't give me the expected result.

    Why ? How could I get the expected result ?

  • Get the number of \r\n in array, i.e. the expected result is: [1, 3, 2]

    How would you do this ?

I use Ruby 1.9.2.

like image 770
Misha Moroshko Avatar asked May 12 '11 06:05

Misha Moroshko


1 Answers

Almost, try this:

s.split /[\r\n]+/
s.scan(/[\r\n]+/).map { |e| e.size/2 }

This gives [1,3,2,1] which is possibly the "real" answer. But otherwise, s.chomp.scan... would give [1,3,2].

like image 185
DigitalRoss Avatar answered Oct 16 '22 09:10

DigitalRoss