Skip to content

Instantly share code, notes, and snippets.

@kirel
Created August 17, 2012 12:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kirel/3378525 to your computer and use it in GitHub Desktop.
Save kirel/3378525 to your computer and use it in GitHub Desktop.
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