Anti-Pattern: Iteratively Building a Collection(robots.thoughtbot.com)
robots.thoughtbot.com
Anti-Pattern: Iteratively Building a Collection
http://robots.thoughtbot.com/iteration-as-an-anti-pattern/
2 comments
The signer_keys_and_uids example can be much cleaner using Enumerator#with_object:
signers.map.with_object({}) { |signer, result| result[signer.key_id] = signer.uids }
signers.map.with_object({}) { |signer, result| result[signer.key_id] = signer.uids }
def signer_keys_and_uids signers.inject({}) do |result, signer| result.merge(signer.key_id => signer.uids) end end
builds not only one but two new hash objects on each iteration, while the "bad" code does neither. Array to Hash is probably best done using Hash[]