Inside the Rails code, people tend to use the Enumerable#inject method to create hashes, like this:
somme_enum.inject({}) do |hash, element|
hash[element.foo] = element.bar
hash
end
While this appears to have become a common idiom, does anyone see an advantage over the “naive” version, which would go like:
hash = {}
some_enum.each { |element| hash[element.foo] = element.bar }
The only advantage I see for the first version is that you do it in a closed block and you don’t (explicitly) initialize the hash. Otherwise it abuses a method unexpectedly, is harder to understand and harder to read. So why is it so popular?
Beauty is in the eye of the beholder. Those with some functional programming background will probably prefer the
inject-based method (as I do), because it has the same semantics as thefoldhigher-order function, which is a common way of calculating a single result from multiple inputs. If you understandinject, then you should understand that the function is being used as intended.As one reason why this approach seems better (to my eyes), consider the lexical scope of the
hashvariable. In theinject-based method,hashonly exists within the body of the block. In theeach-based method, thehashvariable inside the block needs to agree with some execution context defined outside the block. Want to define another hash in the same function? Using theinjectmethod, it’s possible to cut-and-paste theinject-based code and use it directly, and it almost certainly won’t introduce bugs (ignoring whether one should use C&P during editing – people do). Using theeachmethod, you need to C&P the code, and rename thehashvariable to whatever name you wanted to use – the extra step means this is more prone to error.