ruby - 换行位置

标签 ruby string

给定一个字符串,返回字符串中换行符开头的字符位置数组的最有效方法是什么?

text =<<_
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in 
culpa qui officia deserunt mollit anim id est laborum.
_

预期:

find_newlines(text) # => [0, 80, 155, 233, 313, 393]

我发布我自己的答案。我愿意接受最快的方式作为接受的答案。


此处的基准测试结果将在添加新答案时更新

require "fruity"

compare do
  padde1 {find_newlines_padde1(text)}
  digitalross1 {find_newlines_digitalross1(text)}
  sawa1 {find_newlines1(text)}
  sawa2 {find_newlines2(text)}
end

# Running each test 512 times. Test will take about 1 second.
# digitalross1 is faster than sawa2 by 5x ± 0.1
# sawa2 is faster than sawa1 by 21.999999999999996% ± 1.0%
# sawa1 is faster than padde1 by 4.0000000000000036% ± 1.0%

最佳答案

def find_newlines text
  s = 0
  [0] + text.to_a[0..-2].map { |e| s += e.size }
end

如前所述,对 1.9 使用 text.each_line.to_a。调用 each_line 也适用于 1.8.7,但比仅调用 to_a.

慢 20%

关于ruby - 换行位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14941036/

相关文章:

ruby-on-rails - Rails 4.0.2 支持 HTML5

ruby-on-rails - ckfinder 或 corefive.com/projects/filemanager 的 rails 连接器

python - 如何找到字符串中任何一组字符的第一个索引

regex - 允许 A-Za-z0-9 的 Ruby 正则表达式

ruby - 在 Mac 上通过 export http_proxy 使用 Ruby 和 Charles Proxy

ruby - FactoryGirl 未在构建中传递参数

c++ - 挣扎于文本计数器

java - 删除 String 中除某些符号之外的所有符号

arrays - 获取数组而不是字符串

字符指针和数组