Skip to content

Instantly share code, notes, and snippets.

@domgetter
Last active August 29, 2015 14:23
Show Gist options
  • Save domgetter/615094aa7be44c2db81f to your computer and use it in GitHub Desktop.
Save domgetter/615094aa7be44c2db81f to your computer and use it in GitHub Desktop.
I swear there's a use for these.
class Hash
def decompose
each_pair.each_with_index.each_with_object([{},{}]) { |((k,v), i), (f, s)| f[k], s[i] = i, v }
end
def decompose_to_a
each_pair.each_with_index.each_with_object([{},[]]) { |((k,v), i), (f, s)| f[k], s[i] = i, v }
end
end
{:a => "hello", :b => "world"}.decompose
#=> [{:a=>0, :b=>1}, {0=>"hello", 1=>"world"}]
{name: "John J", email: "[email protected]"}.decompose
#=> [{:name=>0, :email=>1}, {0=>"John J", 1=>"[email protected]"}]
{name: "John J", email: "[email protected]"}.decompose_to_a
#=> [{:name=>0, :email=>1}, ["John J", "[email protected]"]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment