|
The GP's point is that Ruby doesn't require a built-in method that specifically sums an array to still get a clean, terse operation. You can use #inject to apply an arbitrary operation to (operator, last result, current element) and arrive at a result. For example, given a list of numbers, you can generate a bitwise OR mask easily: [1,2,3,4,5].inject(:|)
What this does is iterate over the list and apply ($last_result | $current_element) and return the result, which is passed on as $last_result to the next iteration. $last_result is 0 by default. This is equivalent to (as of PHP 5.4): array_reduce([1,2,3,4,5], function($v, $e) { return $v | $e; }, 0);
Or prior to PHP 5.3: function or_mask($v, $e) { return $v | $e; }
array_reduce(array(1,2,3,4,5), "or_mask", 0);
It's doable in both languages, but Ruby's functional language lineage and its object-oriented nature results in an exceptionally clean approach. |