I have a couple of answers that I wrote up for this exercise. Both of my methods work. I'm hoping to get some feedback on each and how I could improve them, if needed.
The idea is to take a string, such as 'abc' and return an array like this: ['a', 'ab', 'abc']
For the second method, I used #map
, but I'm not sure if this is the best way to achieve my desired result.
def substrings(string)
subbed = []
(0..string.length-1).each do |i|
subbed.push(string.slice(0..i))
end
return subbed
end
def substrings2(string)
string.split('').map.with_index do |c,i|
string.slice(0..i)
end
end
print substrings2('abc')