'string' to ['s', 'st', 'str', 'stri', 'strin', 'string']

How about this?

s = 'string'
res = s.length.times.map {|len| s[0..len]}
res # => ["s", "st", "str", "stri", "strin", "string"]

The more declarative I can come up with:

s = "string"
1.upto(s.length).map { |len| s[0, len] } 
#=> ["s", "st", "str", "stri", "strin", "string"]

You can use Abbrev in Standard Library

require 'abbrev'
s = Abbrev::abbrev(['string']).keys
puts s.inspect

I must add the other way to use this after requiring the Abbrev library, with the .abbrev method added to Array:

require 'abbrev'
s = ['string'].abbrev.keys
puts s.inspect

If the order is important to match your return in the question, just call .sort on keys.

Tags:

Ruby