gpt4 book ai didi

ruby - 从字符串中获取前 N 个字符而不剪切整个单词

转载 作者:数据小太阳 更新时间:2023-10-29 06:56:35 25 4
gpt4 key购买 nike

我想知道是否有一种简单的方法可以在不切割整个单词的情况下从字符串中仅获取 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 ...

最佳答案

只需使用带有分隔符选项的截断:

truncate("Once upon a time in a world far far away", length: 17)
# => "Once upon a ti..."
truncate("Once upon a time in a world far far away", length: 17, separator: ' ')
# => "Once upon a..."

获取更多信息:truncate helper in rails API documentation

关于ruby - 从字符串中获取前 N 个字符而不剪切整个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16396590/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com