加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 04:30:08 所属栏目:百科 来源:网络整理
导读:我想知道是否有一种简单的方法可以从字符串中仅获取N个符号而不会切割整个单词. 例如,我有产品和产品描述信息.描述长度是70到500个符号,但我想只显示前70个符号,如下所示: Coca-Cola is the most popular and biggest-selling soft drink in history,as wel
我想知道是否有一种简单的方法可以从字符串中仅获取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"

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读