user21033168
user21033168

Reputation: 444

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

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

Answers (6)

vgoff
vgoff

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

Arup Rakshit
Arup Rakshit

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

Nakilon
Nakilon

Reputation: 35093

s.chars.zip.inject{ |i,j| i << i.last + j.first }

Upvotes: 5

tokland
tokland

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

Frank Schmitt
Frank Schmitt

Reputation: 30815

Another variant (this will include the empty string in the result):

s.each_char.inject([""]) {|a,ch| a << a[-1] + ch}

This

  • starts with an array containing the empty string [""]
  • for each char ch in the string, appends ch to the last result a[-1] + ch
  • adds this to the result array

Upvotes: 0

Sergio Tulentsev
Sergio Tulentsev

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

Related Questions