Skip to content

Instantly share code, notes, and snippets.

@sorah
Last active August 29, 2015 13:59
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 sorah/10451004 to your computer and use it in GitHub Desktop.
Save sorah/10451004 to your computer and use it in GitHub Desktop.
def parse(str)
tokens = str.scan(/(.+?)([,=]|\z)/).flatten
pairs = []
stack = []
while token = tokens.shift
case token
when "="
stack << token
when ","
stack << token
if tokens.first != ',' && 2 <= stack.size
pairs << stack.dup
stack.clear
end
else
stack << token
end
end
pairs << stack.dup unless stack.empty?
pairs = pairs.inject([]) { |r, pair|
if !pair.find{ |_| _ == '='.freeze } && r.last
r.last.push(*pair)
r
else
r << pair
end
}
pairs.each(&:pop)
Hash[pairs.map{ |_| _.join.split(/=/,2) }]
end
p parse("a=b,c=d") # {"a"=>"b", "c"=>"d"}
p parse("aa=b=,,c=d,e=f,g,h,i=j") # {"aa"=>"b=,", "c"=>"d", "e"=>"f,g,h", "i"=>"j"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment