array_sum
-
We can get the sum of an array of integers using a combination of Ruby’s
Enumerable#injectmethod withFixnum#+.PHP
$numbers = array(1, 2, 3); $result = array_sum($numbers); print $result."\n"; // => 6
Ruby
result = [2, 2, 2, 2].inject {|sum, element| sum + element } puts result # => 6
The
ActiveSupportlibrary that comes with Rails includes anEnumerable#summethod to simplify this operation.Rails
[1, 2, 3].sum
see also
Looking for Rails or PHP web application development, integration, and training?
Rails for PHP is brought to you by Maintainable Software. Get custom web applications and personalized training from the authors of the book and website.

