Skip to content

Instantly share code, notes, and snippets.

@MFQ
Last active June 25, 2016 19:57
Show Gist options
  • Save MFQ/c9922a97a658f46c9b993a300bae853b to your computer and use it in GitHub Desktop.
Save MFQ/c9922a97a658f46c9b993a300bae853b to your computer and use it in GitHub Desktop.
require "byebug"
def fetch_values(str)
keys=str.scan(/\w*\s+(?=\=)|\w*+(?=>\=)/)
values = str.scan(/(?<=")\w+(?=")/)
root_key=str.scan(/(?<=^<)+\w*/)
h={}
keys.each_with_index { |key, index| h[key.strip!] = values[index] }
h
end
line_of_code = [
'<tag1 value = "HelloWorld">',
'<tag2 name = "Name1">',
'</tag2>',
'</tag1>'
]
def parse(strings)
stack = []
hash = {}
strings.each do |s|
if ( (s.scan(/^</) ) && (s.scan(/^<\//).empty?) )
stack.push(s)
else
eval_string = stack.pop
eval_string_key = eval_string.scan(/(?<=^<)+\w*/).first
evaluated_hash = fetch_values(eval_string)
if (stack.empty?)
byebug
hash[eval_string_key]={} unless (hash[eval_string_key])
hash[eval_string_key][:attributes] = evaluated_hash
else
parent_key = stack.first.scan(/(?<=^<)+\w*/).first
byebug
if (hash[parent_key])
hash[parent_key] = {}
hash[parent_key][:children] = [] unless (hash[parent_key])
hash[parent_key][:children] << { eval_string_key.dup => evaluated_hash.dup }
end
end
end
end
hash
end
puts(parse(line_of_code))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment