Ruby: inject
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. :)
