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

What is the most elegant way to do

'string' => ['s', 'st', 'str', 'stri', 'strin', 'string'] 

I try to think of one liner, but I canโ€™t get there.
Any solutions are welcome, thanks.

+6
source share
6 answers

You can use Abbrev in the standard library

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

I have to add another way to use this by requiring the Abbrev library, with the .abbrev method added to Array:

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

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

+5
source

How about this?

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

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"] 
+6
source
 s.chars.zip.inject{ |i,j| i << i.last + j.first } 
+5
source

Another option (this will contain an empty string as a result):

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

it

  • starts with an array containing an empty string [""]
  • for each char ch in the string, adds ch to the last result a[-1] + ch
  • adds this to the results array
0
source
 s = "string" s.each_char.with_object([""]){|i,ar| ar << ar[-1].dup.concat(i)}.drop(1) #=> ["s", "st", "str", "stri", "strin", "string"] 
0
source

Source: https://habr.com/ru/post/944855/


All Articles