array_sum

Returns the sum of values in an array.

PHP

$a = array(2, 4, 6, 8);
echo array_sum($a);
// => 20

Ruby

a_var = [2, 4, 6, 8];
puts a_var.inject {|sum,x| sum ? sum + x : x };
# => 20

In the code above, the return value from the ruby code will be nil if the array used is empty. This is not exactly the same behaviour as PHP, since the array_sum() function will always return a number. We can force ruby to always return a float (or an int) too, even if the array is empty, by adding a bit of type casting to the final result:

Ruby

a_var = [];
puts a_var.inject {|sum,x| sum ? sum + x : x }.to_f;
# => 0.0
By | 2009-10-15T22:42:43+00:00 April 5th, 2009|Categories: PHP, Ruby|Tags: , , , |2 Comments

About the Author:

2 Comments

  1. John April 9, 2009 at 1:43 am

    in RoR you can just use Enumerable#sum such as:

    puts [2, 4, 6, 8].sum;
    
  2. Josso March 7, 2010 at 6:14 pm

    If you’re not using Ruby on Rails, you can easily just make your own .sum 🙂

    [code]
    class Array;
    def sum;
    inject( nil ) { |sum,x| sum ? sum+x : x };
    end;
    end
    [/code]

    The result will be the following:

    [code]
    [1,2,3].sum # => 6
    [‘1′,’2′,’3’].sum # => 123
    [‘a’,’b’,’c’].sum # => ‘abc’
    [[‘a’], [‘b’,’c’]].sum # => [‘a’, ‘b’, ‘c’]
    [/code]

    If you’re not sure about the type of the array and only are using it with ints, you might want to replace sum+x with sum.to_i+x.to_i

Comments are closed.

This Is A Custom Widget

This Sliding Bar can be switched on or off in theme options, and can take any widget you throw at it or even fill it with your custom HTML Code. Its perfect for grabbing the attention of your viewers. Choose between 1, 2, 3 or 4 columns, set the background color, widget divider color, activate transparency, a top border or fully disable it on desktop and mobile.

This Is A Custom Widget

This Sliding Bar can be switched on or off in theme options, and can take any widget you throw at it or even fill it with your custom HTML Code. Its perfect for grabbing the attention of your viewers. Choose between 1, 2, 3 or 4 columns, set the background color, widget divider color, activate transparency, a top border or fully disable it on desktop and mobile.