Search code examples
rubyenumerable

Ruby enumerable take first elements until condition is not met


I built my own class and I made it enumerable and now I want to take as many elements as possible, starting from the first one, so long as let's say the sum of them isn't higher than 10. I'm leaning towards a take_while but I'm not sure how to write it.

If you have any other ideas I'm open to them as well. Thanks in advance.


Solution

  • You can do it this way:

    a = [1, 2, 13, 24, 5, 0]
    sum = 0
    a.take_while { |i| sum+=i; sum < 10  } 
    #=> [1, 2]