Skip to content

Instantly share code, notes, and snippets.

@sirupsen
Last active December 22, 2015 13:38
Show Gist options
  • Save sirupsen/6480217 to your computer and use it in GitHub Desktop.
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.
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