ChrisWilson
ChrisWilson

Reputation: 459

How to parse text by new lines?

I have some text that spans multiple lines, and I want to organize it by each new line. An example text is:

Save $5.00 on Candy with Your Pickup Purchase

Other

when you purchase $15.00 worth of candy. Offer valid only when 
Exp 02/09/2019

I'm looking to put each new line in a different array, but not sure how to differentiate the new lines from each other.

Upvotes: 3

Views: 692

Answers (2)

Noah
Noah

Reputation: 570

You can use:

> str = <<e
> First Line
> Second line
> 
> 
> Fifth Line
> 
> Seventh Line
> e
# => "First Line\nSecond line\n\n\nFifth Line\n\nSeventh Line\n" 

> str.split("\n")
# => ["First Line", "Second line", "", "", "Fifth Line", "", "Seventh Line"]

It will split the string into an array separated by new line characters.

Each element in array represents text line, empty text line represents empty line.

Upvotes: 5

sawa
sawa

Reputation: 168071

<<~_.lines
Save $5.00 on Candy with Your Pickup Purchase

Other

when you purchase $15.00 worth of candy. Offer valid only when 
Exp 02/09/2019
_
# =>
# [
#   "Save $5.00 on Candy with Your Pickup Purchase\n",
#   "\n",
#    "Other\n",
#    "\n",
#    "when you purchase $15.00 worth of candy. Offer valid only when \n",
#    "Exp 02/09/2019\n"
# ]

Upvotes: 3

Related Questions