Get a list of all the prefixes of a string

ruby

Solution

A quick benchmark:

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

And the winner is:

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

Problem

is there any inbuilt function in the Ruby `String` class that can give me all the prefixes of a string in Ruby. Something like: ``` "ruby".all_prefixes => ["ruby", "rub", "ru", "r"] ``` Currently I have made a custom function for this: ``` 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 ``` But I am looking for something more rubylike, less code and something magical. Note: of course it goes without saying `original_string` should remain as it is.

Original source