Created
November 1, 2021 12:20
-
-
Save jonelf/16567f3eebc6182c833dc59be26df7e5 to your computer and use it in GitHub Desktop.
Checks if the {} are balanced.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
test_data = ["{dsfgsdf}", "{asdf}, {sdfsdf}", "{{dfgd}, {sadf}}", "sdfd}{", "{asdfsad}, {sdfs}}", "{{asdf},{sdfsdf}"] | |
test_data.each { |s| | |
res = s.split(//).reduce(0) { |sum, c| | |
break sum if sum < 0 | |
sum +=1 if c == "{" | |
sum -=1 if c == "}" | |
sum | |
} | |
puts s + " is #{res != 0 ? "no ":""}good!" | |
} |
JSON strings can contain {}.
`test_data = ["{dsfgsdf}", "{asdf}, {sdfsdf}", "{{dfgd}, {sadf}}", "sdfd}{", "{asdfsad}, {sdfs}}", "{{asdf},{sdfsdf}", '{"test{{{"}, {"{{{fest"}']
test_data.each { |s|
instring = false;
res = s.split(//).reduce(0) { |sum, c|
break sum if sum < 0
instring = !instring if c == '"'
if !instring
sum +=1 if c == "{"
sum -=1 if c == "}"
end
sum
}
puts s + " is #{res != 0 ? "no ":""}good!"
}
`
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output:
{dsfgsdf} is good!
{asdf}, {sdfsdf} is good!
{{dfgd}, {sadf}} is good!
sdfd}{ is no good!
{asdfsad}, {sdfs}} is no good!
{{asdf},{sdfsdf} is no good!