结合Ruby中的段落

时间:2017-08-10 04:37:54

标签: ruby

我有一个字符串:

  

"他真的不了解我,但那里有一种微弱的认识。我是带草莓的女孩。他的女儿偶尔可能会说的那个女孩。五年前那个女孩和妈妈挤在一起,

     姐姐,就像他向她展示的那个年龄最大的孩子一样,拥有勇敢的勋章。她父亲的奖章在矿井中蒸发。他记得吗?有什么关系?他粗暴地重复着。让她挺身而出普里姆在我身后歇斯底里地尖叫着。她像一个恶习一样把她瘦弱的手臂包裹在我周围。"

如何将这两段合并成Ruby中的一个大段?

4 个答案:

答案 0 :(得分:2)

String#squeeze来救援:

input.squeeze($/)

答案 1 :(得分:2)

简单的技巧:

> string.split.join(" ")
另一个:

> string.gsub!(/\s+/, ' ')

如果您使用的是Rails,则会提供 String#squish

> string.squish

注意:以上所有方法都会删除多余的空格以及换行符,并将其作为单个段落。

<强>输出:

#=> "He doesnt know me really, but theres a faint recognition there. I am the girl who brings the strawberries. The girl his daughter might have spoken of on occasion. The girl who five years ago stood huddled with her mother and sister, as he presented her, the oldest child, with a medal of valor. A medal for her father, vaporized in the mines. Does he remember that? What does it matter? he repeats gruffly. Let her come forward. Prim is screaming hysterically behind me. Shes wrapped her skinny arms around me like a vice."

答案 2 :(得分:1)

如果你有像

这样的文字
  

     

这意味着有两个换行符,如下所示:

  

前   BREAK

     

BREAK

     

所以你要做的就是用空格替换两个连续的BREAK。

separated = "before\n\nafter"
combined = separated.gsub(/\n+/, " ")

请注意,这里没有关于文本结构或段落的任何上下文。

答案 3 :(得分:1)

我假设中断是在单词上,所以应该在两个子串之间插入一个空格(而不是说,&#34; ... bicy \ n \ ncle ...&#34;)。我还允许删除应该删除的错误空格。

def join_em(str)
  str.gsub(/(?:\s*\n){2,}/, ' ')
end

join_em("The cat is back.\n\nThe dog never left.")
  #=> "The cat is back. The dog never left."
join_em("The cat is back.  \n  \t \nThe dog never left.")
  #=> "The cat is back. The dog never left."