Skip to content

Instantly share code, notes, and snippets.

@secretfader
Last active January 1, 2016 22:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save secretfader/8211310 to your computer and use it in GitHub Desktop.
Save secretfader/8211310 to your computer and use it in GitHub Desktop.
Ruby Array Conundrum
elements = [["accesses.2013.12", "17"], ["accesses.2013.12", "18"], ["accesses.2013.12", "19"], ["accesses.2013.12", "20"], ["accesses.2013.12", "21"], ["accesses.2013.12", "22"], ["accesses.2013.12", "23"], ["accesses.2013.12", "24"], ["accesses.2013.12", "25"], ["accesses.2013.12", "26"], ["accesses.2013.12", "27"], ["accesses.2013.12", "28"], ["accesses.2013.12", "29"], ["accesses.2013.12", "30"], ["accesses.2013.12", "31"], ["accesses.2014.1", "01"]]
#
# I need to pair down this array into something usable, like:
#
elements = [
{
key: 'accesses.2013.12',
days: [ 17, 18, 19 ]
},
{
key: 'accesses.2014.1',
days: [1]
}
]
# keys are the unique elements from the first portion of each nested array.
# any ideas? Thank you!
@micahredding
Copy link

This format is a bit different, but seems usable. Anything I'm missing?

output = {}
elements.each do |element|
key = element.first
value = element.last
output[key] ||= []
output[key] << value
end

output

output = {'key' => [value,value]}

@secretfader
Copy link
Author

This is even better than what I outlined originally. Thank you, Micah.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment