Created
June 19, 2017 11:43
-
-
Save andreaseger/07b5a1127894d8115830896816eec3ac to your computer and use it in GitHub Desktop.
list of arrays to nested hash tree
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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
deep_merge stuff is copied from active_support