2011-06-04 58 views

回答

39
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"] 
+23

'str.split(/ \ s + /,n + 1)[0 ... n] .join('')'会提高性能。 – sawa 2011-06-04 10:11:58

+1

这将得到前4个单词,而不是3. – 2014-05-15 17:14:10

+3

@ZackXu确保您使用'...'范围字面值,而不是'..'。三个点不包括第n个值。 – 2014-05-15 17:19:06

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 
+4

改进:'trunc = s [/(\ s * \ S +){#{n}} /]'。你不需要'strip'。 – sawa 2011-06-04 09:43:46

+1

@sawa:你可以把它(和你的'split'方法的版本)作为答案,改进和澄清现有的答案是值得的。 – 2011-06-04 18:06:13

+0

@sawa,并添加一个显示加速的基准。 – 2011-06-04 21:40:55

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) * ' ' 
4

如果它的轨道4.2(有truncate_words)

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