Skip to content

Instantly share code, notes, and snippets.

@andreaseger
Created June 19, 2017 11:43
Show Gist options
  • Save andreaseger/07b5a1127894d8115830896816eec3ac to your computer and use it in GitHub Desktop.
Save andreaseger/07b5a1127894d8115830896816eec3ac to your computer and use it in GitHub Desktop.
list of arrays to nested hash tree
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'minitest', require: false
end
require 'minitest/autorun'
module DeepMerge
refine Hash do
def deep_merge(other_hash, &block)
dup.deep_merge!(other_hash, &block)
end
def deep_merge!(other_hash, &block)
other_hash.each_pair do |current_key, other_value|
this_value = self[current_key]
self[current_key] = if this_value.is_a?(Hash) && other_value.is_a?(Hash)
this_value.deep_merge(other_value, &block)
else
if block_given? && key?(current_key)
yield(current_key, this_value, other_value)
else
other_value
end
end
end
self
end
end
end
class NestArrayFooTest < Minitest::Test
using DeepMerge
def work(arrays)
arrays
.map { |e| e.reverse.reduce { |inner, key| inner.nil? ? key : { key => inner } } }
.reduce({}) { |a, e| a.deep_merge(e) }
end
def test_it_does_something_useful1
assert_equal({ a: { b: { c: :d } } }, work([%i[a b c d]]))
end
def test_it_does_something_useful
assert_equal({ a: { b: { c: :d, e: :f } } }, work([%i[a b c d], %i[a b e f]]))
end
end
@andreaseger
Copy link
Author

deep_merge stuff is copied from active_support

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