Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string by whitespace but retain \n - Ruby

Tags:

ruby

I have a ruby file that reads files and splits the text into an array using split(' '). The problem is that these text files contain newline characters, and I would like to retain those newline characters. For example, if I run the following code

"Lorem ipsum\ndolor sit amet".split(' ')

I get the output of

["Lorem", "ipsum", "dolor", "sit", "amet"]

Why does split remove the newline character? How can i retain \n in my array?

like image 337
fbonetti Avatar asked Dec 11 '12 02:12

fbonetti


1 Answers

Michael Berkowski's comment on your question is correct.

If you want to work around this case, use a regular expression:

"Lorem ipsum\ndolor sit amet".split(/ /)
#=> ["Lorem", "ipsum\ndolor", "sit", "amet"] 
like image 50
Ryan Bigg Avatar answered Sep 28 '22 14:09

Ryan Bigg