Skip to content
Novus Examples
rb658 B

Ruby — Stack (Enumerable, blocks, custom error)

A realistic Ruby snippet: a Stack class that mixes in Enumerable, yields blocks, raises a custom error class, and uses string interpolation and symbol-to-proc — for testing highlighters, RuboCop, and parsers.

Preview — first 40 linesrb
# frozen_string_literal: true

# A generic stack: a class that mixes in Enumerable, uses blocks,
# and raises a custom error.
class Stack
  include Enumerable

  class EmptyError < StandardError; end

  def initialize
    @items = []
  end

  def push(item)
    @items.push(item)
    self
  end

  def pop
    raise EmptyError, "stack is empty" if @items.empty?

    @items.pop
  end

  def each(&block)
    @items.reverse_each(&block)
  end

  def size
    @items.size
  end
end

stack = Stack.new
%w[alpha beta gamma].each { |word| stack.push(word) }

puts "top: #{stack.pop}"
puts "remaining: #{stack.map(&:upcase).join(', ')}"
puts "size: #{stack.size}"

Specifications

Language
Ruby
Kind
realistic snippet
Lines
39
Encoding
UTF-8
Line Endings
LF

What is a .rb file?

Ruby (.rb) is a plain-text source file for the Ruby programming language — a dynamically typed, object-oriented scripting language known for expressive, readable syntax and blocks. Everything is an object, and it is widely used for web development (Rails), scripting, and automation.

How to use this file

Use an example .rb file to test syntax highlighters, the Ruby interpreter, linters and formatters (RuboCop), and parser or language-detection tooling.

Generated by generation/code_samples.py. Free for any use, no attribution required — license.