Reputation: 444
What's the most elegant way of doing
'string'
=> ['s', 'st', 'str', 'stri', 'strin', 'string']
I've been trying to think of a one liner, but I can't quite get there.
Any solutions are welcome, thanks.
Upvotes: 6
Views: 807
Reputation: 11323
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
.
Upvotes: 5
Reputation: 118289
s = "string"
s.each_char.with_object([""]){|i,ar| ar << ar[-1].dup.concat(i)}.drop(1)
#=> ["s", "st", "str", "stri", "strin", "string"]
Upvotes: 0
Reputation: 67900
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"]
Upvotes: 6
Reputation: 30815
Another variant (this will include the empty string in the result):
s.each_char.inject([""]) {|a,ch| a << a[-1] + ch}
This
[""]
a[-1] + ch
Upvotes: 0
Reputation: 230461
How about this?
s = 'string'
res = s.length.times.map {|len| s[0..len]}
res # => ["s", "st", "str", "stri", "strin", "string"]
Upvotes: 12