Beth Knight - 8 months ago 56

Ruby Question

I'm doing a codewar where you need to find the sum of positive numbers in an array. I was able to find a solution except for when the test arrays are empty or all the elements are negative. How to I return 0 instead of nil?

Here is my solution...

`def positive_sum(arr)`

arr.select {|x| x > 0}.reduce :+

end

Answer

There's no need to do both `select`

and `reduce`

. You can check the value of `x`

in your `reduce`

block:

```
def positive_sum(arr)
arr.reduce(0) do |sum, x|
if x > 0
sum + x
else
sum
end
end
end
positive_sum([10, -3, 20, -8])
# => 30
positive_sum([])
# => 0
positive_sum([-1, -5])
# => 0
```

Of course, you can make this a oneliner if you prefer:

```
def positive_sum(arr)
arr.reduce(0) {|sum, x| x > 0 ? sum + x : sum }
end
```