ruby – 获取字符串的所有前缀列表

前端之家收集整理的这篇文章主要介绍了ruby – 获取字符串的所有前缀列表前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
Ruby String类中是否有任何内置函数可以为我提供Ruby中字符串的所有前缀.就像是:
"ruby".all_prefixes => ["ruby","rub","ru","r"]

目前我已为此制作了自定义功能

def all_prefixes search_string
  dup_string = search_string.dup
  return_list = []
  while(dup_string.length != 0)
    return_list << dup_string.dup
    dup_string.chop!
  end 
 return_list 
end

但我正在寻找更多的rubylike,更少的代码和神奇的东西.
注意:当然不用说original_string应保持不变.

解决方法

快速基准:
require 'fruity'

string = 'ruby'

compare do   

  toro2k do
    string.size.times.collect { |i| string[0..i] }
  end

  marek_lipka do
    (0...(string.length)).map{ |i| string[0..i] }
  end

  jorg_w_mittag do
    string.chars.inject([[],'']) { |(res,memo),c| 
      [res << memo += c,memo] 
    }.first
  end

  jorg_w_mittag_2 do
    acc = ''
    string.chars.map {|c| acc += c }
  end

  stefan do
    Array.new(string.size) { |i| string[0..i] }
  end

end

最终获胜者是:

Running each test 512 times. Test will take about 1 second.
jorg_w_mittag_2 is faster than stefan by 19.999999999999996% ± 10.0%
stefan is faster than marek_lipka by 10.000000000000009% ± 10.0%
marek_lipka is faster than jorg_w_mittag by 10.000000000000009% ± 1.0%
jorg_w_mittag is similar to toro2k
原文链接:https://www.f2er.com/ruby/267751.html

猜你在找的Ruby相关文章