Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Balanced brackets conditional issue

I’ve been looking into Ruby and felt I was learning quite a bit. I’m currently trying to solve the balanced brackets algorithm but struggling with a condition. Here’s what I have:

def balanced?(list_of_brackets)
    if list_of_brackets.length % 2 != 0
        false
    else
        stack = []
        bracket_sets = {
            '{' => '}', 
            '[' => ']', 
            '(' => ')'
        }
        list_of_brackets.chars do |bracket|
            if bracket == "{" or "[" or "("
                puts "#{bracket} is an opening bracket"
            else
                puts "#{bracket} is a closing bracket"
            end
        end
    end
    stack.empty?
end

puts balanced?('{}()[]')

The result I get is:

{ is an opening bracket
} is an opening bracket
( is an opening bracket
) is an opening bracket
[ is an opening bracket
] is an opening bracket

The closing brackets are somehow getting through the first condition. I’m missing something here but I can’t spot it. Maybe another set of eyes can help me here. I’d appreciate any help and/or advice!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The if statement if bracket == "{" or "[" or "(" needs to have a bracket == X for each or condition in the statement. Change:

if bracket == "{" or "[" or "("

to

if bracket == "{" or bracket == "[" or bracket ==  "("

…and that should work. The full code would be:

def balanced?(list_of_brackets)
    if list_of_brackets.length % 2 != 0
        false
    else
        stack = []
        bracket_sets = {
            '{' => '}', 
            '[' => ']', 
            '(' => ')'
        }
        list_of_brackets.chars do |bracket|
            if bracket == "{" or bracket == "[" or bracket ==  "("
                puts "#{bracket} is an opening bracket"
            else
                puts "#{bracket} is a closing bracket"
            end
        end
    end
    stack.empty?
end

puts balanced?('{}()[]')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading