Leading substrings exercise 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')
What you're looking for is known as a "scan" in functional programming.  Surprisingly, ruby's Enumerable, which is where this method belongs (since what you're doing is not, ultimately, specific to strings), does not provide a scan method or its equivalent.

But we can write one easily enough:

module Enumerable
  def scans
    reduce([]) {|m,x| m &lt;&lt; (m.last || []) + [x]}
  end  
end


Now we have a general purpose method which we can use like so:

[9] pry(main)&gt; (1..5).to_a.scans
=&gt; [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]]


Your original problem now becomes a simple delegation to scans:

[14] pry(main)&gt; 'abc'.split('').scans.map(&amp;:join)
=&gt; ["a", "ab", "abc"]