Skip to content

Instantly share code, notes, and snippets.

@joshuastr
Created April 29, 2016 15:00
Show Gist options
  • Save joshuastr/7743f81393deb761a8e31eb651336bc4 to your computer and use it in GitHub Desktop.
Save joshuastr/7743f81393deb761a8e31eb651336bc4 to your computer and use it in GitHub Desktop.
sum = 0
arr.each do |x|
if yield(x)
sum += x
end
end
sum
end
# now we can sum_if with various blocks, ex:
# sum if even:
a = sum_if([1,2,3,4,5]) do |i|
i % 2 == 0
end
puts a
# sum if > 3
b = sum_if([1,2,3,4,5]) do |i|
i > 3
end
puts b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment