Home > katas > Sum of positive (8kyu) [Ruby]
Sum of positive (8kyu) [Ruby]
Chek kata on Codewars
Description:
You get an array of numbers, return the sum of all of the positives ones.
Example [1,-4,7,12] => 1 + 7 + 12 = 20
Note: if there is nothing to sum, the sum is default to 0.
Solution 1.1
Let's use reduce
method to solve this task.
It executes a reducer function (that you provide) on each element of the array, resulting in single output value.
It is almost a textbook example for reducer.
def positive_sum(arr)
arr.reduce(0) {|acc, cur| acc + (cur > 0 ? cur : 0)}
end
Solution 1.2
def positive_sum(arr)
arr.select{|num| num > 0}.reduce(0, :+)
end
Solution 2.1
Also we can use sum
from Enumerables.
def positive_sum(arr)
arr.select{|num| num > 0}.sum
end
Solution 2.2
def positive_sum(arr)
arr.select(&:positive?).sum
end
Solution 3.1
Another approach will be to loop over the array and sum all positive numbers.
def positive_sum(arr)
sum = 0
arr.each do |num|
if num > 0
sum += num
end
end
sum
end
Solution 3.2
def positive_sum(arr)
sum = 0
arr.each do |num|
if num.positive?
sum += num
end
end
sum
end