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

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

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"] 

你可以这样做:

 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的改进(希望我仍然是数学家,这将是一个定理的一个伟大名称):

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

如果你必须处理大于s中单词数的n ,那么你可以使用这个变体:

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

如果它来自rails 4.2(具有truncate_words),这可能会跟随

 string_given.squish.truncate_words(number_given, omission: "") 

你可以使用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编程,您就会知道清晰度是一种重要的风格选择。

连接的简写是*所以这个语法str.split.first(n) * ' '是等价的和更短的(更惯用,对于不str.split.first(n) * ' '来说不太清楚)。

您也可以使用take而不是first以便以下内容执行相同的操作

 a.split.take(2) * ' '