如何将字符串截断为前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"]
str.split(/\s+/, n+1)[0...n].join(' ')
可以提高性能。 - sawa...
范围字面量而不是..
。三个点将排除第n个值。 - user513951truncate(my_string, :length => 300, :separator => ' ')
其中300为字符数。你将无法选择单词数量,但也并不是那么糟糕! - Nima Izadimy_string.truncate(300, separator: ' ')
吧?http://apidock.com/rails/String/truncate - Yo Ludkes = "what's the best way to truncate a ruby string to the first n words?"
n = 6
trunc = s[/(\S+\s+){#{n}}/].strip
trunc = s[/(\s*\S+){#{n}}/]
n
,则可以使用以下变体:s[/(\S+(\s+)?){,#{n}}/].strip
trunc = s[/(\s*\S+){#{n}}/]
。不需要使用 strip
。 - sawasplit
方法的版本)作为一个答案,对现有答案的改进和澄清是值得的。 - mu is too shorts[/(\S+(\s+)?){,#{n}}/].strip
。 - mu is too shortstr.split.first(n).join(' ')
,其中n可以是任何数字。>> a='apple orange pear banana pineaple grapes'
=> "apple orange pear banana pineaple grapes"
>> b=a.split.first(2).join(' ')
=> "apple orange"
join
的简写是 *
,因此这个语法 str.split.first(n) * ' '
是等效且更短的写法(更具惯用性,对于初学者来说可能不是很清晰)。first
的替代方法 take
,所以下面的写法也可以实现同样的功能。a.split.take(2) * ' '
string_given.squish.truncate_words(number_given, omission: "")