Created
July 28, 2016 08:21
-
-
Save lcguida/9924d9a4e5781572c2c3cb9fbe59a7da to your computer and use it in GitHub Desktop.
Math helpers for collection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module CollectionMath | |
class << self | |
# Returns nil instead of 0 for an empty array | |
def sum_values(collection) | |
values = if block_given? | |
collection.map{ |item| yield item }.compact | |
else | |
collection | |
end | |
return nil if collection.empty? | |
values.sum | |
end | |
# Average helper | |
# Return nils for an empty array | |
def average(collection) | |
values = if block_given? | |
collection.map{ |item| yield item }.compact | |
else | |
collection | |
end | |
return nil if collection.empty? | |
values.sum / values.size | |
end | |
end | |
end |
Not for what I made that for. Rails will raise errors already. I need the values to be nil if not valid.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's better to raise custom errors, for example:
raise ArgumentError, "Empty value" if collection.empty?