Skip to content

Instantly share code, notes, and snippets.

@philosodad
Last active December 24, 2015 20:19
Show Gist options
  • Save philosodad/6856705 to your computer and use it in GitHub Desktop.
Save philosodad/6856705 to your computer and use it in GitHub Desktop.
Monkey patch of the Hash class to convert all string keys to symbols at arbritray depth
require "minitest/autorun"
class Hash
def symogriform
symogriformed = {}
symogrified = self
symogrified.keys.each do |key|
if symogrified[key].is_a?(Hash)
symogrified[key] = symogrified[key].symogriform
end
end
symogriformed.merge!(symogrify(symogrified))
symogriformed
end
def symogrify part
part.keys.inject({}){|hash, key| hash.merge({symog(key) => part[key]})}
end
def symog key
key.is_a?(String) ? key.to_sym : key
end
end
describe Hash do
describe "symogriform" do
it "should convert keys to symbols" do
{"A" => :a, "B" => :b}.symogriform.must_equal({A: :a, B: :b})
end
it "should convert keys at arbitrary layers to symbols" do
{"A" => {"A" => "a"}, "B" => {"B" => {"C" => {}}}}.symogriform.must_equal({A: {A: "a"}, B: {B: {C: {}}}})
end
it "should not error out with non-string keys" do
{1 => "a", 2 => "a"}.symogriform.must_equal({1 => "a", 2 => "a"})
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment