Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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.

like image 406
user21033168 Avatar asked May 13 '13 08:05

user21033168


2 Answers

How about this?

s = 'string'
res = s.length.times.map {|len| s[0..len]}
res # => ["s", "st", "str", "stri", "strin", "string"]
like image 155
Sergio Tulentsev Avatar answered Oct 14 '22 08:10

Sergio Tulentsev


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"]
like image 33
tokland Avatar answered Oct 14 '22 07:10

tokland