Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a multi line string to an array in Ruby using line breaks as delimiters

I would like to turn this string

"P07091 MMCNEFFEG

P06870 IVGGWECEQHS

SP0A8M0 VVPVADVLQGR

P01019 VIHNESTCEQ"

into an array that looks like in ruby.

["P07091 MMCNEFFEG", "P06870 IVGGWECEQHS", "SP0A8M0 VVPVADVLQGR", "P01019 VIHNESTCEQ"]

using split doesn't return what I would like because of the line breaks.

like image 955
Sharon Yang Avatar asked Jun 23 '14 16:06

Sharon Yang


1 Answers

This is one way to deal with blank lines:

string.split(/\n+/)

For example,

string = "P07091 MMCNEFFEG

P06870 IVGGWECEQHS

SP0A8M0 VVPVADVLQGR




P01019 VIHNESTCEQ"

string.split(/\n+/)
  #=> ["P07091 MMCNEFFEG", "P06870 IVGGWECEQHS",
  #    "SP0A8M0 VVPVADVLQGR", "P01019 VIHNESTCEQ"]

To accommodate files created under Windows (having line terminators \r\n) replace the regular expression with /(?:\r?\n)+/.

like image 114
Cary Swoveland Avatar answered Sep 22 '22 10:09

Cary Swoveland