array_sum

  • We can get the sum of an array of integers using a combination of Ruby’s Enumerable#inject method with Fixnum#+.

    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 ActiveSupport library that comes with Rails includes an Enumerable#sum method 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.