• Home
  • About

stonean

Feeds:
Posts
Comments

Ruby: inject

November 14, 2008 by stonean

Inject is a powerfully cool method provided by the Enumerable module. At first I was a little confused by the name. I didn’t know what it meant. Here’s a simple example:

an_array = [1, 2, 3, 4, 5, 6]

def x10(v)
  v * 10
end

an_array.inject([]) do |sum, num|
  sum << x10(num)
end

=> [10, 20, 30, 40, 50, 60]

So, by passing [] into the inject method, the variable sum is initialized as an empty array. Now the inject method will iterate over the array an add the value return by x10 to the new array (sum).

Calling inject on a hash:

def convert_hash(hsh)
  hsh.inject({}) do |sum, aray|
    sum.merge( { aray[0] => some_conversion_method(aray[1]) } )
  end
end

**Notice that inject when called on a hash will pass the key and value in one array: [key, value]. Hence the aray[0] and aray[1] calls.

Of course, since you are creating an entirely new hash, you could change the key if you wanted. This was just a simple example.

Anyway…just a short update. It’s been a while since I shared. :)

Posted in Ruby | No Comments Yet

  • Open Source


    Lockdown (GitHub)
    RuHL (GitHub)

  • Recommend Me

  • twitter: stonean

    • @ubermuda that's good to know, thank you! 16 hours ago
    • @chanmix51 cool, thanks! 16 hours ago
    • In vi, :set list to show hidden characters, to revert, :set nolist Very handy. 18 hours ago
    • Team just did their first PechaKucha [ http://vurl.me/EEP ] session. I love this format and am very impressed with results! 1 day ago
    • Just posted Lauren's new 'Curry Chicken Salad' recipe to http://lowsaltlauren.com . 3 days ago
  • Categories

    classy-inheritance Code Style DataMapper Fusion git Haml Interview Questions jQuery lockdown Merb MysqlUtils Process Quick Tips REST RSpec Ruby RubyOnRails rubytrends Stage thoughts Uncategorized


  • Archives

    • November 2009
    • May 2009
    • April 2009
    • March 2009
    • February 2009
    • January 2009
    • December 2008
    • November 2008
    • October 2008
    • August 2008
    • July 2008
    • June 2008
    • May 2008
    • April 2008
    • March 2008
    • February 2008
    • January 2008
    • December 2007
    • November 2007

Blog at WordPress.com.

Theme: Mistylook by Sadish.