将字符串截断为前n个单词

时间:2011-06-04 08:56:40

标签: ruby string

将字符串截断为前n个单词的最佳方法是什么?

4 个答案:

答案 0 :(得分:41)

n = 3
str = "your long    long   input string or whatever"
str.split[0...n].join(' ')
 => "your long long"


str.split[0...n] # note that there are three dots, which excludes n
 => ["your", "long", "long"]

答案 1 :(得分:9)

你可以这样做:

s     = "what's the best way to truncate a ruby string to the first n words?"
n     = 6
trunc = s[/(\S+\s+){#{n}}/].strip

如果你不介意复制。

你也可以通过调整空格检测来应用Sawa's改进(希望我仍然是一位数学家,这对于一个定理来说是个很好的名字):

trunc = s[/(\s*\S+){#{n}}/]

如果您必须处理的n大于s中的字数,那么您可以使用此变体:

s[/(\S+(\s+)?){,#{n}}/].strip

答案 2 :(得分:4)

如果它来自rails 4.2(有truncate_words)

,则可以关注
string_given.squish.truncate_words(number_given, omission: "")

答案 3 :(得分:3)

您可以使用str.split.first(n).join(' ') n是任何数字。

原始字符串中的连续空格将替换为返回字符串中的单个空格。

例如,请在irb中尝试:

>> a='apple    orange pear banana   pineaple  grapes'
=> "apple    orange pear banana   pineaple  grapes"
>> b=a.split.first(2).join(' ')
=> "apple orange"

这种语法非常清楚(因为它不使用正则表达式,按索引排列数组)。如果你用Ruby编程,你就会知道清晰度是一种重要的风格选择。

join的简写为* 所以这个语法str.split.first(n) * ' '是等同的,更短(更惯用,对于没有经验的人来说不那么明确)。

您也可以使用take代替first 所以下面会做同样的事情

a.split.take(2) * ' '