def check(s) open = ['(', '[', '{', '<'] close = [')', ']', '}', '>'] stack = [] for j in 0..s.length do if open.include?(s[j]) stack.push(s[j]) end if close.include?(s[j]) if (stack.length == 0) return false else index = close.index(s[j]) open_bracket = open[index] if stack[stack.length-1] == open_bracket stack.pop() else return false end end end end return (stack==[]) end s1 = "[{([[[<>]]])(<>)(){}}]" s2 = "]()(){<>}[[()]]" s3 = "[(sjd),'2'],{2:3}, [<>]" s4 = "{[[[[((()))]]<]>]}" puts(check(s1)) # True puts(check(s2)) # False puts(check(s3)) # True puts(check(s4)) # False