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"

相关文章

以下代码导致我的问题: class Foo def initialize(n=0) @n = n end attr_accessor :n d...
这是我的spec文件,当为上下文添加测试“而不是可单独更新用户余额”时,我得到以下错误. require 's...
我有一个拦截器:DevelopmentMailInterceptor和一个启动拦截器的inititializer setup_mail.rb. 但我想将...
例如,如果我有YAML文件 en: questions: new: 'New Question' other: recent: ...
我听说在RSpec中避免它,let,let !,指定,之前和主题是最佳做法. 关于让,让!之前,如果不使用这些,我该如...
我在Rails中使用MongoDB和mongo_mapper gem,项目足够大.有什么办法可以将数据从Mongoid迁移到 Postgres...