ruby – 从字符串中获取前N个字符而不删除整个单词

前端之家收集整理的这篇文章主要介绍了ruby – 从字符串中获取前N个字符而不删除整个单词前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想知道是否有一种简单的方法可以从字符串中仅获取N个符号而不会切割整个单词.

例如,我有产品和产品描述信息.描述长度是70到500个符号,但我想只显示前70个符号,如下所示:

Coca-Cola is the most popular and biggest-selling soft drink in
history,as well as the best-known brand in the world.

On May 8,2011,Coca-Cola celebrated its 125thanniversary. Created in
1886 in Atlanta,Georgia,by Dr. John S. Pemberton,Coca-Cola was
first offered as a fountain beverage at Jacob’s Pharmacy by mixing
Coca-Cola syrup with carbonated water.

那么,普通的子串方法会给我:

Coca-Cola is the most popular and biggest-selling soft drink in histor

我需要一个方法来获得这个:

Coca-Cola is the most popular and biggest-selling soft drink in ...

解决方法

s = "Coca-Cola is the most popular and biggest-selling soft drink in history,as well as the best-known brand in the world."
s = s.split(" ").each_with_object("") {|x,ob| break ob unless (ob.length + " ".length + x.length <= 70);ob << (" " + x)}.strip
#=> "Coca-Cola is the most popular and biggest-selling soft drink in"
原文链接:https://www.f2er.com/ruby/269144.html

猜你在找的Ruby相关文章