All original content is created in Ukrainian. Not all content has been translated yet. Some posts may only be available in Ukrainian.Learn more

Task to check the correctness of bracket placement (Ruby)

Post cover: Task to check the correctness of bracket placement (Ruby)
This content has been automatically translated from Ukrainian.
The condition for the task is as follows. Create a function valid_braces that takes a string consisting only of brackets: ()[]{}.
The function should return true if all brackets open and close in the correct order, or false if the brackets are incorrectly placed.
Example of method execution:
valid_braces("()")         → true  
valid_braces("({[]})")     → true  
valid_braces("({[)]}")     → false  
valid_braces("(((()")      → false  
valid_braces("{[()]}[]")   → true

How does bracket checking work?

This task is classically solved using a stack — a data structure that works on the principle of "last in, first out".
The idea is to add opening brackets to the stack, and when we encounter a closing bracket — check if it matches the one on top of the stack. If so — remove it from the stack; if not — the string is incorrect.

Test (RSpec) for checking the method

RSpec.describe '#valid_braces' do
  it 'returns true for valid brackets' do
    expect(valid_braces('()')).to eq(true)
    expect(valid_braces('([])')).to eq(true)
    expect(valid_braces('{[()]}')).to eq(true)
    expect(valid_braces('{[()]}[]')).to eq(true)
  end

  it 'returns false for invalid brackets' do
    expect(valid_braces('[(])')).to eq(false)
    expect(valid_braces('({[)]}')).to eq(false)
    expect(valid_braces('((')).to eq(false)
    expect(valid_braces(']')).to eq(false)
  end
end

Method valid_braces

def valid_braces(string)
  stack = []
  pairs = { ')' => '(', ']' => '[', '}' => '{' }

  string.each_char do |char|
    if pairs.values.include?(char)
      stack.push(char)
    elsif pairs.keys.include?(char)
      return false if stack.pop != pairs[char]
    end
  end

  stack.empty?
end

Algorithm operation principle

  1. Each time we see an opening bracket — we add it to the stack.
  2. If we encounter a closing one — we compare it with the last opening (from the top of the stack).
  3. If they match — we continue.
  4. If not — we immediately return false.
  5. If the stack is empty after processing the string — all brackets were correctly closed, so we return true.
This approach can be used for paired symbols of any type — not just brackets. It is well-suited for checking the correctness of nested structures, for example, in parsers or HTML analyzers.

This post doesn't have any additions from the author yet.

How do Scratch courses help children develop soft skills?
Apr 11, '25 18:24

How do Scratch courses help children develop soft skills?

meme code
meme code@memecode
Apr 24, '25 20:17

Fixing minikube "You are trying to run the amd64 binary on an M1 system."

meme code
meme code@memecode
Apr 24, '25 20:55

Fixing minikube on Mac with M1 (abandoning qemu, running on docker)

meme code
meme code@memecode
Where to find an older version of Google Chrome and download it? Using an old Mac as an example.
Apr 25, '25 23:02

Where to find an older version of Google Chrome and download it? Using an old Mac as an example.

meme code
meme code@memecode
May 9, '25 19:27

[FIXED] cannot load such file -- html/pipeline (LoadError) occurs during rails generate thredded:install

meme code
meme code@memecode
Task: Convert a Roman numeral to decimal (Ruby)
May 20, '25 12:05

Task: Convert a Roman numeral to decimal (Ruby)

meme code
meme code@memecode
How to find the maximum subarray sum in Ruby
May 22, '25 11:01

How to find the maximum subarray sum in Ruby

meme code
meme code@memecode
Google Ads for Dummies: A Step-by-Step Guide for a Successful Start
May 28, '25 10:21

Google Ads for Dummies: A Step-by-Step Guide for a Successful Start

meme code
meme code@memecode
What is jemalloc and how does it relate to Ruby / Ruby on Rails
May 30, '25 11:53

What is jemalloc and how does it relate to Ruby / Ruby on Rails

meme code
meme code@memecode
Jun 5, '25 01:52

[Fixed] uninitialized constant ActiveSupport::LoggerThreadSafeLevel::Logger (NameError)

meme code
meme code@memecode
The preview in the network tab after the Chrome update has become very small.
Jun 5, '25 18:23

The preview in the network tab after the Chrome update has become very small.

meme code
meme code@memecode
What is the HEIC format and why simply renaming it to .jpg is a bad idea
Jun 15, '25 18:17

What is the HEIC format and why simply renaming it to .jpg is a bad idea

meme code
meme code@memecode