Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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
- 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?)
- hash[eval_string_key] = evaluated_hash
- else
- parent_key = stack.first.scan(/(?<=^<)+\w*/).first
- if (hash[parent_key])
- hash[parent_key][eval_string_key]= evaluated_hash
- else
- hash[parent_key] = {}
- hash[parent_key][eval_string_key]= evaluated_hash
- end
- end
- end
- end
- hash
- end
- line_of_code = [
- '<tag1 value = "HelloWorld">',
- '<tag2 name = "Name1">',
- '</tag2>',
- '</tag1>'
- ]
- puts(parse(line_of_code))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement