Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Count Values in an Array (See related posts)

This modifies the Array class to allow for easy summing
class Array
  def total
    t = 0
    self.each { |v| t += v }
    t
  end
end

Use it like this:
[1,2,2,3].total  # => 8

Comments on this post

peter posts on Jun 14, 2006 at 20:06
Try this. It does the same thing but is more concise:

class Array
  def total
   self.inject(nil) { |p, i| p ? p+i : i }
  end
end


It also allows you to do this:

['a','b','c'].total  # => "abc"

You need to create an account or log in to post comments to this site.


Click here to browse all 5147 code snippets

Related Posts