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 at the 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 one (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?
11 Apr 18:24

How do Scratch courses help children develop soft skills?

meme code
meme code@memecode
24 Apr 20:17

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

meme code
meme code@memecode
24 Apr 20:55

Setting up 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.
25 Apr 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
09 May 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)
20 May 12:05

Task: Convert a Roman numeral to decimal (Ruby)

meme code
meme code@memecode
How to find the maximum subarray sum in Ruby
22 May 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
28 May 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
30 May 11:53

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

meme code
meme code@memecode
05 Jun 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.
05 Jun 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
15 Jun 18:17

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

meme code
meme code@memecode