Skip to content

Instantly share code, notes, and snippets.

@jonelf
Created November 1, 2021 12:20
Show Gist options
  • Save jonelf/16567f3eebc6182c833dc59be26df7e5 to your computer and use it in GitHub Desktop.
Save jonelf/16567f3eebc6182c833dc59be26df7e5 to your computer and use it in GitHub Desktop.
Checks if the {} are balanced.
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!"
}
@jonelf
Copy link
Author

jonelf commented Nov 1, 2021

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!

@jonelf
Copy link
Author

jonelf commented Nov 1, 2021

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