-
-
Save unimatrixZxero/6238586 to your computer and use it in GitHub Desktop.
This file contains 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
module Abyss | |
ROUNDTRIP = {}.tap { |abyss| abyss.default = abyss }.freeze | |
def to_abyss(obj = self) | |
case obj | |
when Hash | |
obj.inject({}) { |h,(k, v)| h.update k => to_abyss(v) }.tap { |h| h.default = ROUNDTRIP } | |
when Array | |
obj.map { |e| to_abyss(e) } | |
else | |
obj | |
end | |
end | |
module_function :to_abyss | |
public :to_abyss | |
end | |
Hash.send :include, Abyss | |
if $0 == __FILE__ | |
require 'test/unit' | |
class TestAbyss < Test::Unit::TestCase | |
def test_hash_keys | |
abyss = { a: 'hash', nested: { hash: true } }.to_abyss | |
assert_equal abyss[:a], 'hash' | |
assert_equal abyss[:nested][:hash], true | |
end | |
def test_abyss | |
abyss = { a: 'hash', nested: { hash: true } }.to_abyss | |
assert_equal abyss[:abyss], {} | |
assert_equal abyss[:abyss][:abyss], {} | |
assert_equal abyss[:nested][:abyss], {} | |
assert_equal abyss[:nested][:abyss][:abyss], {} | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment