Last active
December 22, 2015 13:38
-
-
Save sirupsen/6480217 to your computer and use it in GitHub Desktop.
Quick and dirty way to check whether a string of parentheses are balanced.
This file contains hidden or 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
def balanced?(string) | |
string.each_char.inject(0) { |open, char| | |
return false if open < 0 | |
char == '(' ? open + 1 : open - 1 | |
} == 0 | |
end | |
p balanced?("()((()))") | |
p balanced?("())))") | |
p balanced?("()(((())") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment