Skip to content

Instantly share code, notes, and snippets.

@lcguida
Created July 28, 2016 08:21
Show Gist options
  • Save lcguida/9924d9a4e5781572c2c3cb9fbe59a7da to your computer and use it in GitHub Desktop.
Save lcguida/9924d9a4e5781572c2c3cb9fbe59a7da to your computer and use it in GitHub Desktop.
Math helpers for collection
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
@rpossan
Copy link

rpossan commented Jul 28, 2016

It's better to raise custom errors, for example:

raise ArgumentError, "Empty value" if collection.empty?

@lcguida
Copy link
Author

lcguida commented Jul 28, 2016

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