-1

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.

Roman Kiselenko
  • 43,210
  • 9
  • 91
  • 103
Robert
  • 178
  • 1
  • 8
  • 1
    Your question look like __write code for me__. What have you tried so far? – Roman Kiselenko Oct 24 '15 at 12:12
  • did you read the example for [`take_while`](http://ruby-doc.org/core-2.2.3/Enumerable.html#method-i-take_while) in docs? – shivam Oct 24 '15 at 12:15
  • Yes, I don't understand how to do something else in the block after the conditions are met, I tried with `my_enum.take_while do |x| sum + x <= 10 sum += x end` (I have sum defined as 0 before that) – Robert Oct 24 '15 at 12:18

1 Answers1

2

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]
shivam
  • 16,048
  • 3
  • 56
  • 71
  • Thank you very much, I kept testing and saw that I could write a `do..end` block with an `if` inside but your solution looks much better :) – Robert Oct 24 '15 at 13:12