Rails中的字数?

sen*_*hil 16 ruby word-count

假设我有一个标题和正文的博客模型.我如何显示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)

  • 怎么样"添加一些摇滚乐"?这里有三个单词,而你的变体会找到五个单词. (2认同)

小智 17

也:

"Lorem Lorem Lorem".split.size
=> 3
Run Code Online (Sandbox Code Playgroud)

  • 我更喜欢这个.简单.我在`split`之前添加了`squish`. (2认同)

小智 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)。