Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.