Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a list of all the prefixes of a string

Tags:

ruby

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.

like image 935
Sahil Dhankhar Avatar asked Aug 06 '13 10:08

Sahil Dhankhar


1 Answers

No, there is no built-in method for this. You could do it like this:

def all_prefixes(string)
  string.size.times.collect { |i| string[0..i] }
end
all_prefixes('ruby')
# => ["r", "ru", "rub", "ruby"] 
like image 148
toro2k Avatar answered Oct 16 '22 03:10

toro2k