hellogoodbye hellogoodbye - 8 months ago 20
Ruby Question

Break loop when sum of array gets over certain value in Ruby

I want to break my while loop when the sum of the array that I am appending to gets to a certain number (20). Here's what I've tried:

p1_score = []
p2_score = []

until p1_score.inject(:+) >= 20 || p2_score.inject(:+) >= 20 do

but I get the following error:

`play_game': undefined method `>=' for nil:NilClass (NoMethodError)


The problem is that when p1_score = [], p1_score.inject(:+) returns nil.

A quick fix - and I cannot say for sure whether this is the best solution without seeing more context of your code - would be to explicitly convert this value into an integer, by using the alternate Enumerable#inject(initial, sym) syntax:

until p1_score.inject(0, :+) >= 20 || p2_score.inject(0, :+) >= 20 do