Created
August 3, 2017 09:35
-
-
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)
This file contains hidden or 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
| 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