Skip to content

Instantly share code, notes, and snippets.

@aarti
Created December 13, 2016 08:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aarti/3ea1b6b0474120fddde87d9b1bb62aee to your computer and use it in GitHub Desktop.
Save aarti/3ea1b6b0474120fddde87d9b1bb62aee to your computer and use it in GitHub Desktop.
def deserialize(input)
h = {}
l = 0
stack = []
curr_string = ""
while l < input.length do
case input[l]
when "{" #state = DICT_START
curr_string = ""
when ":" #state = VALUE_START
stack.push(curr_string)
curr_string = ""
when "}", "," #state = DICT_END
if curr_string != "" then
stack.push(curr_string)
end
if stack.length > 0 then
val = stack.pop
key = stack.pop
stack.push({key => val})
end
curr_string = ""
else
curr_string+=input[l]
end
l+=1
end
stack.each {|n| h.merge!(n)}
h
end
p deserialize("{a:test,b:test1,c:test3}")
p deserialize("{a:{b:test1}}")
p deserialize("{a:{b:{c:test1}}}")
p deserialize("{a:{b:{c:test1}},d:123}")
@aarti
Copy link
Author

aarti commented Dec 13, 2016

Input: "{a:test,b:test1,c:test3}" #string
Output: {"a"=>"test", "b"=>"test1", "c"=>"test3"} #hash nested to any level
Input: "{a:{b:test1}}"
Output: {"a"=>{"b"=>"test1"}}
Input: "{a:{b:{c:test1}}}"
Output: {"a"=>{"b"=>{"c"=>"test1"}}} #hash nested to any level
Input: "{a:{b:{c:test1}},d:123}"
Output: {"a"=>{"b"=>{"c"=>"test1"}}, "d"=>"123"}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment