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.
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With