2013-04-24 92 views
1

我想打一个条件语句,将检查:检查字符串中有超过15个字符的字

comment.user.name 

(这可能会返回类似"Montgomery Philips Ridiculouslylonglastname")包含大于15的任何话字符。

喜欢的东西:

if comment.user.name.split(" ").??? 

回答

7

这个怎么样?

comment.user.name.split.any? { |x| x.length > 20 } 

这里是美妙的enumerable mixin文档。

+2

如果它只是被'split'而不是'分裂( '')'? – Mischa 2013-04-24 07:46:17

+0

@Mischa嗯,我以为他的原始字符串上有'.'分割。我可能是错的。 – squiguy 2013-04-24 07:46:51

+0

来自问题的引用:(可能会返回类似“Montgomery Philips Ridiculouslylonglastname”) – Mischa 2013-04-24 07:47:48

0
w = "Montgomery Philips Ridiculouslylonglastname" 
w.split().any? {|i| i[16] != nil} #=> true 

"Montgomery Philips".split().any? {|i| i[16] != nil} #=> false 
0
def contains_longer_than length 
    comment.user.name.split.select{|x| x.length > length}.size > 0 
end 
2

使用正则表达式是不是创建一个全新的阵列清洁只是为了检查是否字符串匹配某种模式(正则表达式是为这个订做!):

('a'*19+' '+'a'*19) =~ /[^ ]{20}/ #=> nil 
('a'*19+' '+'a'*20) =~ /[^ ]{20}/ #=> 20 

这又是什么意思:

$ ruby -rbenchmark -e 'long_string = ([("a"*20)]*1000).join(" ") 
puts Benchmark.measure{ 100.times{ long_string.split.any? { |x| x.length > 20 } } }' 
#=> 0.050000 0.000000 0.050000 ( 0.051955) 
$ ruby -rbenchmark -e 'long_string = ([("a"*20)]*1000).join(" ") 
puts Benchmark.measure{ 100.times{ long_string =~ /[^ ]{20}/ } }' 
#=> 0.000000 0.000000 0.000000 ( 0.000128) 

而且正则表达式版本〜比string.split.any?快365倍!

+0

'\ S'不是我想的。非空格字符和单词字符之间有区别。 – pguardiario 2013-04-24 10:21:39

+0

@pguardiario你是对的;最接近'split('')'的匹配模式可能是'[^]'(它也比\ S'更快)(答案更新) – mdesantis 2013-04-24 12:21:07

5

仅供参考(如你已经找到一个合适的答案),用正则表达式做:

/\b[a-z]{15,}\b/i 

如果你找到一个匹配,有超过15个字符(标题20)一个字的长度。

+0

感谢15/20混合的正则表达式方法 – Jaqx 2013-04-24 07:55:04

0

Loamhoof是接近,但还有一个更简单的正则表达式:

/\w{16}/