假设我有一个标题和正文的博客模型.我如何显示Body中的单词数和Title中的字符数?我希望输出是这样的
标题:Lorem身体:Lorem Lorem Lorem
这篇文章的字数为3.
YOU*_*YOU 35
"Lorem Lorem Lorem".scan(/\w+/).size
=> 3
Run Code Online (Sandbox Code Playgroud)
更新:如果你需要将摇滚乐作为一个单词匹配,你可以这样做
"Lorem Lorem Lorem rock-and-roll".scan(/[\w-]+/).size
=> 4
Run Code Online (Sandbox Code Playgroud)
小智 17
也:
"Lorem Lorem Lorem".split.size
=> 3
Run Code Online (Sandbox Code Playgroud)
小智 5
如果您对性能感兴趣,我写了一个快速基准测试:
require 'benchmark'
require 'bigdecimal/math'
require 'active_support/core_ext/string/filters'
# Where "shakespeare" is the full text of The Complete Works of William Shakespeare...
puts 'Benchmarking shakespeare.scan(/\w+/).size x50'
puts Benchmark.measure { 50.times { shakespeare.scan(/\w+/).size } }
puts 'Benchmarking shakespeare.squish.scan(/\w+/).size x50'
puts Benchmark.measure { 50.times { shakespeare.squish.scan(/\w+/).size } }
puts 'Benchmarking shakespeare.split.size x50'
puts Benchmark.measure { 50.times { shakespeare.split.size } }
puts 'Benchmarking shakespeare.squish.split.size x50'
puts Benchmark.measure { 50.times { shakespeare.squish.split.size } }
Run Code Online (Sandbox Code Playgroud)
结果:
Benchmarking shakespeare.scan(/\w+/).size x50
13.980000 0.240000 14.220000 ( 14.234612)
Benchmarking shakespeare.squish.scan(/\w+/).size x50
40.850000 0.270000 41.120000 ( 41.109643)
Benchmarking shakespeare.split.size x50
5.820000 0.210000 6.030000 ( 6.028998)
Benchmarking shakespeare.squish.split.size x50
31.000000 0.260000 31.260000 ( 31.268706)
Run Code Online (Sandbox Code Playgroud)
换句话说,squish使用Very Large Strings™非常慢。除此之外,split速度更快(如果不使用,速度则快两倍squish)。