简单的一条--如何在(比方说)第三段上截断博客文章的文本?并明确地告诉它不呈现图像?
我用的是减价。这能用简单的代码和纯红宝石中的外部宝石以某种“优雅”的方式完成吗?
如果没有,如何最好地实现它?
发布于 2013-04-16 16:47:40
对于截断段落,如下所示的内容应该有效:
def truncate_by_paragraph(text, num=3)
# since I'm not sure if the text will have \r, \n or both I'm swapping
# all \r characters for \n, then splitting at the newlines and removing
# any blank characters from the array
array = text.gsub("\r", "\n").split("\n").reject { |i| i == "" }
array.take(num).join("\n") + ".." # only 2 dots since sentence will already have 1
end要删除图像,可以执行以下操作:
def remove_images(text)
text.gsub(/<img([^>])+/, "")
end那你就可以
truncate_by_paragraph(@text) # will return first 3 paragraphs
truncate_by_paragraph(@text, 5) # will return first 5 paragraphs
remove_images(truncate_by_paragraph(@text)) # 3 paragraphs + no images根据格式设置,您可能希望将第一个方法中的join更改为join("\n\n"),以获得双间距。
另外,如果你真的想要在文本末尾的...,你可能想测试第3段是否有一个点,或者它可能已经有3。
https://stackoverflow.com/questions/16042273
复制相似问题