Balanced brackets conditional issue

Advertisements

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!

>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?('{}()[]')

Leave a ReplyCancel reply