如何用换行来解析文本?

时间:2019-02-04 04:52:17

标签: ruby

我有一些跨越多行的文本,我想按每行新内容进行组织。示例文本为:

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

我希望将每行换成不同的数组,但不确定如何将新行区分开。

2 个答案:

答案 0 :(得分:5)

您可以使用:

> 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"]

它将字符串拆分成一个由换行符分隔的数组。

数组中的每个元素代表文本行,空文本行代表空行。

答案 1 :(得分:3)

<<~_.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"
# ]