Skip to content

Instantly share code, notes, and snippets.

@hmaddocks
hmaddocks / memo.rb
Created January 28, 2025 05:24
A simple Ruby memoization/cache class
class Memo
def initialize
@mutex = Mutex.new
@values = {}
end
def memoize(key = :_default_key)
raise ArgumentError, "Block is required" unless block_given?
@mutex.synchronize do
@hmaddocks
hmaddocks / result.rb
Last active January 25, 2025 20:58
Implementation of a Result monad for Ruby
# frozen_string_literal: true
# Represents an immutable Result object that can contain either a successful value
# or an error message. This implements the Result pattern for handling success/failure
# scenarios in a functional way.
Result = Data.define(:value, :error_message, :creation_location) do
def self.ok(value)
new(value: value, error_message: nil, creation_location: caller_locations(1, 1).first)
end
@hmaddocks
hmaddocks / gist:a126dedb44c72f308912a1f6b8790ff9
Created June 21, 2024 01:06
Refactor Code Found on LinkedIn
# Case 2: Refactor code
class ProjectsCount
def initialize(projects)
@projects = projects
end
def self.call(projects)
new(projects).call
end