Skip to content

Instantly share code, notes, and snippets.

@sixtyfive
Created August 3, 2017 09:35
Show Gist options
  • Select an option

  • Save sixtyfive/7e052d9062baa1b32e875ec968ad8357 to your computer and use it in GitHub Desktop.

Select an option

Save sixtyfive/7e052d9062baa1b32e875ec968ad8357 to your computer and use it in GitHub Desktop.
Examples for how to use Ruby's Array#each_with_object, Array#reduce (thanks to #ruby's Radar and baweaver)
src = [{foo: 1.2, bar: 2.3}, {foo: 3.2, bar: 3.0}]
src.each_with_object({foo: [], bar: []}) { |data, acc| acc[:foo] << data[:foo]; acc[:bar] << data[:bar] }
# => {:foo=>[1.2, 3.2], :bar=>[2.3, 3.0]}
[{foo: 1.2, bar: 2.3}, {foo: 3.2, bar: 3.0}].reduce { |a,b| a.merge(b) { |_,o,n| Array(o) << n } }
# => {:foo=>[1.2, 3.2], :bar=>[2.3, 3.0]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment