Skip to content

Instantly share code, notes, and snippets.

@hyfather
Created October 24, 2011 14:35
Show Gist options
  • Save hyfather/1309177 to your computer and use it in GitHub Desktop.
Save hyfather/1309177 to your computer and use it in GitHub Desktop.
Explains how all Hashes in an Array can be merged.
[{:a => 'alpha'}, {:b => 'beta'}, {:c => 'charlie'}].map(&:to_a)
#=> [[[:a, "alpha"]], [[:b, "beta"]], [[:c, "charlie"]]]
flat_array = [{:a => 'alpha'}, {:b => 'beta'}, {:c => 'charlie'}].map(&:to_a).flatten
#=> [:a, "alpha", :b, "beta", :c, "charlie"]
Hash[*flat_array]
#=> {:a=>"alpha", :b=>"beta", :c=>"charlie"}
# Bringing us to --
class Array
def flatten_hashes
Hash[*self.map(&:to_a).flatten]
end
end
[{:a => 'alpha'}, {:b => 'beta'}, {:c => 'charlie'}].flatten_hashes
#=> {:a => 'alpha', :b => 'beta', :c => 'charlie'}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment