Skip to content

Instantly share code, notes, and snippets.

@sorah sorah/a.rb
Last active Aug 29, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.