PHP to Ruby
Convert PHP code into Ruby!
-
array_sum
Posted on April 5th, 2009 2 commentsReturns 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


