Convert multi-line string to array in Ruby using line breaks as delimiters

I would like to include this line

"P07091 MMCNEFFEG P06870 IVGGWECEQHS SP0A8M0 VVPVADVLQGR P01019 VIHNESTCEQ" 

into an array similar to ruby.

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

using split does not return what I would like due to line breaks.

+12
string arrays ruby
source share
5 answers

This is one way to deal with empty strings:

 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"] 
+29
source share
 string = "P07091 MMCNEFFEG P06870 IVGGWECEQHS SP0A8M0 VVPVADVLQGR P01019 VIHNESTCEQ" 

Using CSV::parse

 require 'csv' CSV.parse(string).flatten # => ["P07091 MMCNEFFEG", "P06870 IVGGWECEQHS", "SP0A8M0 VVPVADVLQGR", "P01019 VIHNESTCEQ"] 

Another way: String#each_line : -

 ar = [] string.each_line { |line| ar << line.strip unless line == "\n" } ar # => ["P07091 MMCNEFFEG", "P06870 IVGGWECEQHS", "SP0A8M0 VVPVADVLQGR", "P01019 VIHNESTCEQ"] 
+5
source share

Creating @Martin answer:

 lines = string.split("\n").reject(&:blank?) 

This will only give you rows that are graded.

+4
source share

Split can take a parameter in the form of a character that will be used for separation, so you can do:

 lines = string.split("\n") 
0
source share

I like to use this as a fairly general method for handling newlines and returns:

 lines = string.split(/\n+|\r+/).reject(&:empty?) 
0
source share

All Articles