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"

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...