Skip to content

Instantly share code, notes, and snippets.

View havenwood's full-sized avatar
:octocat:

Shannon Skipper havenwood

:octocat:
  • Leafly
  • Ashland, Oregon
  • 22:30 (UTC -07:00)
View GitHub Profile
@havenwood
havenwood / skynet.rb
Created May 3, 2022 00:14
A port of the Crystal "skynet" code to Ruby, see https://bugs.ruby-lang.org/issues/18760
require 'async'
require 'async/queue'
def skynet(c, num, size, div)
if size == 1
c << num
else
rc = Async::LimitedQueue.new(div)
sum = 0
div.times do |i|
@havenwood
havenwood / example.rb
Last active April 29, 2022 14:03
Kaprekar's Constant in Ruby
require_relative 'kaprekar'
include Kaprekar
p kaprekar(four_digit_number: 9000).first(10)
#>> [9000, 8991, 8082, 8532, 6174, 6174, 6174, 6174, 6174, 6174]
p kaprekar(four_digit_number: 9000).take_while { _1 != Kaprekar::CONSTANT }
#>> [9000, 8991, 8082, 8532]
# frozen_string_literal: true
source 'https://rubygems.org'
gem 'rack', github: 'rack/rack'
gem 'puma', github: 'puma/puma'
@havenwood
havenwood / store.rb
Created February 8, 2022 05:32
Handling nested PStore transactions (IRC example)
require 'pstore'
class Store
def initialize(relative_path: '.data.pstore')
@store = PStore.new(relative_path, true)
@store.ultra_safe = true
@store.transaction(true) { }
@in_transaction = false
@store
end
@havenwood
havenwood / async.rb
Last active February 12, 2022 17:43
require 'async'
class Enumerator
class Async
module Refinement
refine Enumerable do
def async
Enumerator::Async.new(self)
end
end
@havenwood
havenwood / enumerable.rb
Last active April 24, 2022 20:26
Implementing #each with Ractor- and Async-based concurrency for fun
require 'async'
module Enumerable
module Async
[Array, Hash, Range, Struct].each do |collection|
refine collection do
def each(&block)
super do |value|
Async do
block.call(value)
@havenwood
havenwood / task.rb
Last active February 12, 2022 17:42
Just a overly simplified example of calling methods without arguments concurrently with Async and in parallel with Ractors
require 'async'
module Task
module_function
def async(*method_names)
Async do
method_names.map do |job|
Async do
job.to_proc.call(self)
@havenwood
havenwood / tic_tac_toe.rb
Created December 7, 2021 20:03
Matrix Tic Tac Toe for fun
# frozen_string_literal: true
require 'matrix'
class TicTacToe
BOARD_SIZE = 3
MARKS = {x: -1, o: 1}.freeze
private_constant :MARKS
ROW_MOVES = %i[top middle bottom].freeze
private_constant :ROW_MOVES
@havenwood
havenwood / undigits.rb
Last active November 19, 2022 03:34
Array#undigits
module Undigits
refine Array do
def undigits(base = 10)
reverse.reduce(0) do |acc, digit|
acc * base + digit
end
end
end
end
# When Math.sqrt(2).fdiv(2) is just too zippy.
require 'bigdecimal'
require 'bigdecimal/util'
def i_ish(precision:)
sqrt_2 = 2.to_d.sqrt precision
sqrt_i = Complex sqrt_2 / 2, sqrt_2 / 2
sqrt_i * sqrt_i
end