Skip to content

Instantly share code, notes, and snippets.

@AJFaraday
Created March 14, 2017 14:11
Show Gist options
  • Save AJFaraday/daf04899ee573628c35768548cf1a7fd to your computer and use it in GitHub Desktop.
Save AJFaraday/daf04899ee573628c35768548cf1a7fd to your computer and use it in GitHub Desktop.
How can I do this
# 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
Copy link

def transform_data data
  data.each_with_object({}) do |row, hash|
    hash[row[:a]] ||= {}
    hash[row[:a]][row[:b]] = row[:c]
  end
end

@AJFaraday
Copy link
Author

@jgaskins

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! :)

@jgaskins
Copy link

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