Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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.


Prior to PHP 5.3 this could work as well:

    array_reduce(array(1,2,3,4,5), create_function('$v, $e', 'return $v | $e;'), 0);


I'm really glad that 5.3 got proper anonymous functions. Specifying function bodies as strings to be eval'd makes me twitch.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: