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.
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With