Created
March 14, 2017 14:11
-
-
Save AJFaraday/daf04899ee573628c35768548cf1a7fd to your computer and use it in GitHub Desktop.
How can I do this
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# underpants | |
data = [ | |
{a: 1, b: 1, c: 'a'}, | |
{a: 1, b: 2, c: 'b'}, | |
{a: 2, b: 2, c: 'c'} | |
] | |
# ? | |
new_data = transform_data(data) | |
# profit! | |
new_data[1][1] | |
# => 'a' | |
new_data[1][2] | |
# => 'b' |
jgaskins
commented
Mar 14, 2017
I wrote almost exactly the same code using inject
instead of each_with_object
...
def transform_data(data)
data.inject({}) do |hash, row|
hash[row[:a]] ||= {}
hash[row[:a]][row[:b]] = row[:c]
hash
end
end
I think yours is a little tidier, tho, without having to return hash
from each block.
Thanks! :)
I only use inject
if I'm not modifying anything. If I'm doing any sort of mutation, I use each_with_object
. When building state from scratch, mutation is just faster, so I use each_with_object
waaaaay more than inject
.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment